Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set PUBLIC_URL in create-react-app?

Tags:

reactjs

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.

like image 878
ShutUpILoveYou Avatar asked Sep 02 '18 12:09

ShutUpILoveYou


People also ask

What is PUBLIC_URL in react JS?

To reference assets in the public folder, you need to use an environment variable called PUBLIC_URL . Inside index.html , you can use it like this: <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> Only files inside the public folder will be accessible by %PUBLIC_URL% prefix.

Where is PUBLIC_URL in React?

json or the PUBLIC_URL environment variable that must be set before building the project. When running the react-scripts build script, the %PUBLIC_URL% placeholders inside the index. html file are replaced with the environment variable string.

Does create React app minify code?

If you're using Create React App, please follow the instructions above. This section is only relevant if you configure webpack directly. Webpack v4+ will minify your code by default in production mode.


1 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.

like image 115
Erkka Mutanen Avatar answered Oct 18 '22 20:10

Erkka Mutanen