score:6

You can override the homepage setting using you dev shell environment:

$ export PUBLIC_URL=http://localhost:3000/ 
$ yarn start 

or if you prefer, remove your homepage setting and configure your env before building for production:

$ export PUBLIC_URL=http://example.com/subdir 
$ yarn build

score:8

For people coming here looking for an all-in-one answer which also covers react-router-dom:

  1. Add package.json['homepage'] to be your production url. To be noted, the CRA build step removes the domain part of the url to leave only the path to index.

  2. When building for localhost, do PUBLIC_URL=/ npm run build

  3. Add <base href="%PUBLIC_URL%" /> in your public/index.html page as proposed in this article ; it will provide support for assets (img, css) and will expose the %PUBLIC_URL% to be reused later.

  4. In the component which creates your BrowserRouter (typically App.js or main.js), add:

    const basename = document.querySelector('base')?.getAttribute('href') ?? '/'    
    
  5. use as: <BrowserRouter basename={basename} />

score:47

You can use PUBLIC_URL environment variable to override the homepage for a specific build. Even better have it set in your package.json, for instance:

{
  // ...
  "scripts": {
    "build": "react-scripts build",
    "build-localhost": "PUBLIC_URL=/ react-scripts build"
    // ...
  }
  // ...
}

score:100

Docs for create-react-app explains how to serve same build from different relative paths.

If you put homepage as

"homepage": ".",

assets will be served relative to index.html. You will then be able to move your app from http://mywebsite.com to http://mywebsite.com/relativepath or even http://mywebsite.com/relative/path without having to rebuild it.

For development purposes, serving using yarn start or npm start is good enough. App will be available in localhost


Related Query

More Query from same tag