简体   繁体   中英

Get public URL in index.html after build

I have a reactjs app created with command npx create-react-app my-app , and I build my project using yarn build

package json:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }

Once I build the app index.html looks like below (It has absolute paths for all the static files),

<script type="text/javascript" src="/static/js/main.af2bdfd5.js"></script>
<link href="/static/css/main.097da2df.css" rel="stylesheet">
<link rel="shortcut icon" href="/favicon.ico">

I want to have those sources looks like below (need to give a public URL)

<script type="text/javascript" src="http://localhost:3000/static/js/main.af2bdfd5.js"></script>
<link href="http://localhost:3000/static/css/main.097da2df.css" rel="stylesheet">
<link rel="shortcut icon" href="http://localhost:3000/favicon.ico">

I have tried adding PUBLIC_URL and homepage to package.json but it didn't work.

Just use %PUBLIC_URL% in your link's href and it will fetch the files only if those files are present in the public folder.

Place your files in the public folder and lets assume the file is your icon which you want to access and its name is icon.ico

<link rel="shortcut icon" href="%PUBLIC_URL%/icon.ico">

You don't need to put the absolute url for your files and can just use %PUBLIC_URL% in index.html.

Note : You don't need to add PUBLIC_URL to package.json . It's assigned to the public folder already.

Found a solution,

I used dotenv to set the environment variable. Steps to implement the solution is given below.

1) Install dotenv package.

npm i dotenv

2) As early as possible in the application, require and configure dotenv.

require('dotenv').config()

3) Create a .env file in the root directory of the project. Add environment-specific variables on new lines in the form of NAME=VALUE .

PUBLIC_URL=http://192.168.8.100:3000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM