How to set PUBLIC_URL in create-react-app?

Viewed 34347

How to set PUBLIC_URL in create-react-app?

I use cross-env so that I'm goona set PUBLIC_URL like below.

"start": "cross-env NODE_ENV=dev PUBLIC_URL=http://localhost:8080 react-app-rewired start --scripts-version react-scripts-ts"

And console.log(process.env) show me the right result about NODE_ENV, dev. But PUBLIC_URL is just ' ' that default value.

how can i set PUBLIC_URL? I need two PUBLIC_URL for development and production environment.

2 Answers

Here is my experience on this issue:

create-react-app or CRA system sets the

%PUBLIC_URL%

variable from .env file in the root of the application folder, next to file package.json. There is no need to use PUBLIC_URL in development configuration, in my experience the app runs just fine in development setting. Running

yarn build

on a CRA-initialized React application will set the PUBLIC_URL variable according to the .env file contents. What the .env file should contain then?

No need for brackets or braces, just

.env file contents:

PUBLIC_URL=https://yourdomain.whatever/subdirectory

for example, if your application is served from /public_html/subdirectory.

Additionally, CRA does not support the homepage keyword in its package.json file, so it can be removed and use .env file in the root instead.

Start loads webpack.config in development configuration, which ignores PUBLIC_URL. It starts a development server that serves files at host root. If you need to change port for the development server, use PORT instead.

(Original answer fixed, see comments)

Related