Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Set 'currentScript' as default 'PUBLIC_URL' #3834

Open
MichaelDeBoey opened this issue Jan 17, 2018 · 0 comments
Open

Set 'currentScript' as default 'PUBLIC_URL' #3834

MichaelDeBoey opened this issue Jan 17, 2018 · 0 comments

Comments

@MichaelDeBoey
Copy link
Contributor

MichaelDeBoey commented Jan 17, 2018

Like I suggested in #3708 (comment), currentScript could be a possible default for PUBLIC_URL.

Right now all asset paths are relative (ie /static/media/logo.2e151009.png) to the root of the app.
When setting the PUBLIC_URL environment parameter or the homepage in package.json, the asset paths become absolute (ie https://app.com/static/media/logo.2e151009.png).
Setting these 2 variables is mostly used when you have your app running in a subdirectory on your server.

My proposal is to default the PUBLIC_URL to the root of the app, so there will be less need of setting the PUBLIC_URL or homepage and CRA would need less configuration by default. If it's still necessary to set PUBLIC_URL or homepage, that would still be possible of course. 🙂

The implementation for this could be to check the file-path of the main.*.js script (ref: StackOverflow), which could be accessed by calling document.currentScript (ref: MDN). Since this isn't possible in IE, we could use this answer as a fallback.

function resolvePublicPath() {
  const currentScript = document.currentScript || getCurrentScriptViaFallback();
  const publicPath = currentScript.src
    .split('/static/js')[0] // app root directory
    .split('main.')[0]; // add support for script in app root directory
  
  return `${publicPath}/`;
}
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

2 participants