Skip to content

Set 'currentScript' as default 'PUBLIC_URL' #3834

Open

Description

@MichaelDeBoey

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}/`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions