如何从 package.json 文件设置 NODE_ENV 用于 React。

34

我正在尝试在本地执行React应用程序时,针对多个环境进行目标定位。

1. Development
2. Staging
3. Production

我也在尝试测试任何环境中的离线模式。因此,我配置的脚本如下:

    "staging-server": "nodemon server.js --environment=staging",
    "staging": "concurrently -k  \"npm:staging-server\" \"NODE_ENV='staging' PORT=3003 react-scripts start\"",
    "prod": "npm run build && forever server.js --environment=production"

我能够使用Express内的args获取环境变量,但当我在控制台输入process.env.NODE_ENV时,我的本地UI应用程序仍然只显示开发环境。我也尝试使用相同的行设置staging的NODE_ENV,但仍然没有成功。PORT设置有效,但应用程序在3000和3003两个端口上运行。

如何解决这个问题?我也想了解如何配置staging环境。


你需要执行 eject 命令来进行配置。 - Tien Duong
@TienDuong - 我不想这样做。 - Mithun Shreevatsa
正如文档所述,您不能手动覆盖 NODE_ENV,您必须创建另一个变量。 - Agney
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables。您不能手动覆盖NODE_ENV。 - Tien Duong
2
你可以尝试使用另一个环境变量,例如REACT_APP_ENVIRONMENT而不是NODE_ENV - Tien Duong
4个回答

28
根据文档,我们不能覆盖NODE_ENV,但是可以创建以REACT_APP_开头的自定义变量。因此,我配置如下:
参考:https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
"staging": "concurrently -k  \"npm:staging-server\" \"cross-env REACT_APP_ENVIRONMENT='staging' PORT=3003 react-scripts start\"",

在我的UI应用程序中,我可以通过以下方式将其值作为控制台输出:

console.log('REACT_APP_ENVIRONMENT => ', process.env.REACT_APP_ENVIRONMENT);

嗨,我尝试了这个...但它不起作用!@Mithun。这还有效吗? - Akhila

7

我使用 REACT_APP_STAGE 来构建应用程序,并将其作为 process.env.REACT_APP_STAGE 在我的应用程序中使用。

"scripts": {
    "analyze": "source-map-explorer 'build/static/js/*.js'",
    "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
    "start-js": "react-scripts start",
    "start": "REACT_APP_STAGE=local npm-run-all -p watch-css start-js",
    "build": "npm run build-css && react-scripts build",
    "build-dev": "REACT_APP_STAGE=dev react-scripts build",
    "build-prod": "REACT_APP_STAGE=prod react-scripts build",
    "build-qa": "REACT_APP_STAGE=qa react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },

这是弹射后,我不想使用它。 - Mithun Shreevatsa
1
不需要弹出,这种REACT_APP_方法是可以工作的。这也是您所接受的答案。 - Aman Gupta

1
最简单的方法是直接在命令中添加它:
"scripts": {
    "start": "./node_modules/.bin/nodemon server.js",
    "start:prod": "NODE_ENV=prod node server.js",
  },

1
不行,这个方法行不通,因为我们无法覆盖 NODE_ENV。请参考这里的被接受的答案。 - Hadi KAR
正如 @HadiKAR 所提到的,NODE_ENV 无法被覆盖为您自己的值。 - Gru
你可以像这样在Mac上覆盖ENV变量,但是在Windows上,你需要一个名为cross-env的包(https://www.npmjs.com/package/cross-env)。甚至有很多指南将此作为选项进行了覆盖。 - cnps

0
在 NODE_ENV 前面使用 cross-env。
npm i -g cross-env

"staging": "concurrently -k  \"npm:staging-server\" \"cross-env NODE_ENV='staging' PORT=3003 react-scripts start\"",

2
你不能覆盖 NODE_ENV。 - Alan Deep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接