urlToRequest.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. // we can't use path.win32.isAbsolute because it also matches paths starting with a forward slash
  3. const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i;
  4. function urlToRequest(url, root) {
  5. // Do not rewrite an empty url
  6. if (url === '') {
  7. return '';
  8. }
  9. const moduleRequestRegex = /^[^?]*~/;
  10. let request;
  11. if (matchNativeWin32Path.test(url)) {
  12. // absolute windows path, keep it
  13. request = url;
  14. } else if (root !== undefined && root !== false && /^\//.test(url)) {
  15. // if root is set and the url is root-relative
  16. switch (typeof root) {
  17. // 1. root is a string: root is prefixed to the url
  18. case 'string':
  19. // special case: `~` roots convert to module request
  20. if (moduleRequestRegex.test(root)) {
  21. request = root.replace(/([^~/])$/, '$1/') + url.slice(1);
  22. } else {
  23. request = root + url;
  24. }
  25. break;
  26. // 2. root is `true`: absolute paths are allowed
  27. // *nix only, windows-style absolute paths are always allowed as they doesn't start with a `/`
  28. case 'boolean':
  29. request = url;
  30. break;
  31. default:
  32. throw new Error(
  33. "Unexpected parameters to loader-utils 'urlToRequest': url = " +
  34. url +
  35. ', root = ' +
  36. root +
  37. '.'
  38. );
  39. }
  40. } else if (/^\.\.?\//.test(url)) {
  41. // A relative url stays
  42. request = url;
  43. } else {
  44. // every other url is threaded like a relative url
  45. request = './' + url;
  46. }
  47. // A `~` makes the url an module
  48. if (moduleRequestRegex.test(request)) {
  49. request = request.replace(moduleRequestRegex, '');
  50. }
  51. return request;
  52. }
  53. module.exports = urlToRequest;