You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.6 KiB

4 years ago
  1. 'use strict';
  2. const path = require('path');
  3. const matchRelativePath = /^\.\.?[/\\]/;
  4. function isAbsolutePath(str) {
  5. return path.posix.isAbsolute(str) || path.win32.isAbsolute(str);
  6. }
  7. function isRelativePath(str) {
  8. return matchRelativePath.test(str);
  9. }
  10. function stringifyRequest(loaderContext, request) {
  11. const splitted = request.split('!');
  12. const context =
  13. loaderContext.context ||
  14. (loaderContext.options && loaderContext.options.context);
  15. return JSON.stringify(
  16. splitted
  17. .map((part) => {
  18. // First, separate singlePath from query, because the query might contain paths again
  19. const splittedPart = part.match(/^(.*?)(\?.*)/);
  20. const query = splittedPart ? splittedPart[2] : '';
  21. let singlePath = splittedPart ? splittedPart[1] : part;
  22. if (isAbsolutePath(singlePath) && context) {
  23. singlePath = path.relative(context, singlePath);
  24. if (isAbsolutePath(singlePath)) {
  25. // If singlePath still matches an absolute path, singlePath was on a different drive than context.
  26. // In this case, we leave the path platform-specific without replacing any separators.
  27. // @see https://github.com/webpack/loader-utils/pull/14
  28. return singlePath + query;
  29. }
  30. if (isRelativePath(singlePath) === false) {
  31. // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
  32. singlePath = './' + singlePath;
  33. }
  34. }
  35. return singlePath.replace(/\\/g, '/') + query;
  36. })
  37. .join('!')
  38. );
  39. }
  40. module.exports = stringifyRequest;