getPublicUrlOrPath.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. const { URL } = require('url');
  9. module.exports = getPublicUrlOrPath;
  10. /**
  11. * Returns a URL or a path with slash at the end
  12. * In production can be URL, abolute path, relative path
  13. * In development always will be an absolute path
  14. * In development can use `path` module functions for operations
  15. *
  16. * @param {boolean} isEnvDevelopment
  17. * @param {(string|undefined)} homepage a valid url or pathname
  18. * @param {(string|undefined)} envPublicUrl a valid url or pathname
  19. * @returns {string}
  20. */
  21. function getPublicUrlOrPath(isEnvDevelopment, homepage, envPublicUrl) {
  22. const stubDomain = 'https://create-react-app.dev';
  23. if (envPublicUrl) {
  24. // ensure last slash exists
  25. envPublicUrl = envPublicUrl.endsWith('/')
  26. ? envPublicUrl
  27. : envPublicUrl + '/';
  28. // validate if `envPublicUrl` is a URL or path like
  29. // `stubDomain` is ignored if `envPublicUrl` contains a domain
  30. const validPublicUrl = new URL(envPublicUrl, stubDomain);
  31. return isEnvDevelopment
  32. ? envPublicUrl.startsWith('.')
  33. ? '/'
  34. : validPublicUrl.pathname
  35. : // Some apps do not use client-side routing with pushState.
  36. // For these, "homepage" can be set to "." to enable relative asset paths.
  37. envPublicUrl;
  38. }
  39. if (homepage) {
  40. // strip last slash if exists
  41. homepage = homepage.endsWith('/') ? homepage : homepage + '/';
  42. // validate if `homepage` is a URL or path like and use just pathname
  43. const validHomepagePathname = new URL(homepage, stubDomain).pathname;
  44. return isEnvDevelopment
  45. ? homepage.startsWith('.')
  46. ? '/'
  47. : validHomepagePathname
  48. : // Some apps do not use client-side routing with pushState.
  49. // For these, "homepage" can be set to "." to enable relative asset paths.
  50. homepage.startsWith('.')
  51. ? homepage
  52. : validHomepagePathname;
  53. }
  54. return '/';
  55. }