简体   繁体   中英

How to set env variables to react scripts

I'm building a project that has a backend, and a frontend. I had the idea that'd be cool to have both folders in the same directory with another npm script that runs them.

The problem is that I'm unable to set the port in one of the two packages, that being the frontend.

In my main package.json I have this:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start-app": "cross-env SERVER_PORT=8080 npm start --prefix ./frontend",
    "start-server": "cross-env SERVER_PORT=8080 npm start --prefix ./backend"
  },

And it works for the backend, but doesn't for the frontend.

The frontend has the base configuration.

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

The project runs, but when I look for the process.env, there's no trace of the SERVER_PORT in the FrontEnd but it exists in the BackEnd.

(Backend scripts are the default for a new npm package).

"scripts": {
    "start": "node main.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

CRA uses PORT to define the port variable. Run it like:

 "start": “PORT=8000 react-scripts start"

Additionally since CRA is essentially a static site it doesn't have in itself a concept of env variables - these are NodeJS specific. A few such as PORT and NDOE_ENV are defined for you and used in the dev server. If you wanted to use custom env vars within your React components you can make them available by defining the with the prefix: REACT_APP_ such as REACT_APP_SITENAME for example.

Check out the docs here: https://create-react-app.dev/docs/adding-custom-environment-variables/

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