你应该使用环境变量和 webpack 的 DefinePlugin。此外,您可以使用node-config 自动加载基于您的NODE_ENV 的json 配置文件。
package.json
"scripts": {
"build:dev": "NODE_ENV=development start-something",
"build": "NODE_ENV=production start-something"
}
项目配置结构
config
default.json
{ "api": "https://api.mysite.com/v1" }
staging.json
{ "api": "http://localhost:8000/v1" }
webpack 配置
// node-config will load your staging.json or default.json file here
// depending on what NODE_ENV is
const config = require('config');
plugins: [
// inject window.CONFIG into your app
new webpack.DefinePlugin({
CONFIG: JSON.stringify(config)
})
]
然后在您的反应代码中,您将可以访问特定于环境的配置
componentDidMount() {
// in prod: https://api.mysite.com/v1/user/some-user-id
// in staging: http://localhost:8000/v1/user/some-user-id
return axios(`${CONFIG.api}/user/${this.props.userId}`).then(whatever...)
}
如果您使用的是 Windows,请使用 cross-env 设置您的环境变量。
使用node-config 不是唯一的方法,有几种方法,但我发现它很容易,除非你使用电子。
编辑
由于node-config 使用 nodejs,它通常与 webpack 一起用于前端项目。如果你无法将它与 webpack 集成,你根本不需要使用 node-config,我会这样做:
项目结构
config
default.json
development.json
test.json
index.js
src
...etc
配置文件
// default.json, typically used for production
{
"api": "https://api.mysite.com/v1"
}
// development.json
{
"api": "http://localhost:8000/v1"
}
// index.js
// get process.env via babel-plugin-transform-inline-environment-variables
import production from './default.json';
import development from './development.json';
const { NODE_ENV: env } = process.env;
const config = {
production,
development
};
export default config[env];