简体   繁体   中英

Attaching absolute path to css/js files while building the react app

Is there a way I could have absolute paths to reach js/css files after I build the react app? I tried the homepage thing in package.json which looks like:

  {
    "name": "controller",
    "version": "0.1.0",
    "private": true,
    "homepage": "http://127.0.0.1/controller/",
    "dependencies": {
      "react": "^16.5.2",
      "react-dom": "^16.5.2",
      "react-scripts": "2.0.4"
    },
    "scripts": {
      "start": "PORT=3006 react-scripts start",
      "build": "react-scripts build",
      "test": "react-scripts test",
      "eject": "react-scripts eject"
    },
    "eslintConfig": {
      "extends": "react-app"
    },
    "browserslist": [
      ">0.2%",
      "not dead",
      "not ie <= 11",
      "not op_mini all"
    ]
}

But the final output produced has an output which looks like:

<script src="/controller/static/js/main.38015169.chunk.js"></script>

So the path is from controller . The problem occurs when I try to load the react app from a proxy. The scripts start giving 404 error because it searches the scripts on a different domain. How could I make the part as absolute during the react build?

I would want the referencing to look like:

<script src="http://127.0.0.1/controller/static/js/main.38015169.chunk.js"></script>

I was able to solve this by placing a variable called PUBLIC_URL in the .env file at the root of each react application.

PUBLIC_URL=http://127.0.0.1/controller/

When the build is made, all javascript/CSS paths start from the value of PUBLIC_URL , which is what I had wanted.

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