我在我的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"
}
}
我想您现在可以正常工作了,但是对于其他发现此问题的人,您可以在
.env“ create-react-app”项目根目录下的文件中设置默认环境变量。要分离使用时使用的变量
npm start,npm run build可以再创建两个环境文件-.env.development和.env.production。npm start将设置REACT_APP_NODE_ENV为development,因此它将自动使用该.env.development文件,并npm run build设置REACT_APP_NODE_ENV为production,因此它将自动使用.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.