运行create-react-app构建脚本时如何设置build .env变量?

reactjs Webpack

Itachi猿

2020-03-23

我在我的create-react-app中使用以下环境变量:

console.log(process.env.REACT_APP_API_URL) // http://localhost:5555

当我npm start通过读取.env文件运行时它起作用

REACT_APP_API_URL=http://localhost:5555

我如何像http://localhost:1234执行a 一样设置其他值npm run build

这是我的package.json文件:

{
  "name": "webapp",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "0.9.0"
  },
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

第3119篇《运行create-react-app构建脚本时如何设置build .env变量?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
Tom凯 2020.03.23

我想您现在可以正常工作了,但是对于其他发现此问题的人,您可以在.env“ create-react-app”项目根目录下文件中设置默认环境变量

要分离使用时使用的变量npm startnpm run build可以再创建两个环境文件- .env.development.env.production

npm start将设置REACT_APP_NODE_ENVdevelopment,因此它将自动使用该.env.development文件,并npm run build设置REACT_APP_NODE_ENVproduction,因此它将自动使用.env.production这些中设置的值将覆盖您的中的值.env

如果你与其他人一起工作,并有特定的值到你的机器而已,你可以在覆盖原有的数值.env.development.env.production-通过将这些值到一个新的文件.env.development.local,并.env.production.local分别。

EDIT: I should point out that the environment variables you have set must start with "REACT_APP_", eg. "REACT_APP_MY_ENV_VALUE".

EDIT 2: if you need more than just development, and production, use env-cmd, as specified by this comment.

null 2020.03.23

如果您想使用单独的dotenv文件来构建和/或部署到单独的环境(阶段,产品),则可以使用env-cmd,如下所示:

npm install --save-dev env-cmd
./node_modules/.bin/env-cmd -f ./stage.env npm build

然后只需相应地更新package.json

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "build:stage": "env-cmd -f ./.stage.env npm run-script build"
  },

然后要构建,只需运行以下shell命令:

npm run build:stage

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android