问题描述
我在 create-react-app 中使用以下环境变量:
I'm using the following environment variable in my create-react-app:
console.log(process.env.REACT_APP_API_URL) // http://localhost:5555
它在我通过读取 .env
文件运行 npm start
时起作用:
It works when I run npm start
by reading a .env
file:
REACT_APP_API_URL=http://localhost:5555
如何在执行 npm run build
时设置不同的值,例如 http://localhost:1234
?
How do I set a different value like http://localhost:1234
when executing 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"
}
}
推荐答案
你可以像这样使用process.env.NODE_ENV
:
const apiUrl = process.env.NODE_ENV === 'production' ? process.env.REACT_APP_PROD_API_URL : process.env.REACT_APP_DEV_API_URL;
您需要设置 REACT_APP_PROD_API_URL
和 REACT_APP_DEV_API_URL
.
或者,如果生产 URL 始终相同,您可以简化它:
Or, if the production URL is always the same, you could simplify it:
const apiUrl = process.env.NODE_ENV === 'production' ? 'https://example.com' : process.env.REACT_APP_DEV_API_URL;
Create React App 在构建时将 NODE_ENV
设置为生产",因此您无需担心何时将其设置为生产.
Create React App sets the NODE_ENV
to 'production' for you on build, so you don't need to worry about when to set it to production.
注意:您必须重新启动服务器(例如再次运行 npm start
)以检测环境变量更改.
Note: you must restart your server (e.g. run npm start
again) to detect environment variable changes.
这篇关于运行 create-react-app 构建脚本时如何设置构建 .env 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!