我有一个ApiCaller.js
模块,它生成对我们的应用程序接口服务器的调用以获取数据。它有指向服务器url的const字段API_URL。此API_URL常量更改适用于开发和prod环境。
因此,当我需要部署到开发人员环境时,我需要手动更改指向dev-api-server url (API_URL),反之亦然。
我希望在代码之外使用这些配置参数,并且在构建过程中我希望动态更改它们,以便可以使用不同的设置进行构建。
我正在使用的webpack来捆绑我的javascript,html,css文件。
发布于 2016-07-18 05:42:39
您可以将您的API_URL
存储在webpack配置中:
// this config can be in webpack.config.js or other file with constants
var API_URL = {
production: JSON.stringify('prod-url'),
development: JSON.stringify('dev-url')
}
// check environment mode
var environment = process.env.NODE_ENV === 'production' ? 'production' : 'development';
// webpack config
module.exports = {
// ...
plugins: [
new webpack.DefinePlugin({
'API_URL': API_URL[environment]
})
],
// ...
}
现在,在您的ApiCaller
中,您可以使用API_URL
作为已定义的变量,这取决于process.env.NODE_ENV
ajax(API_URL).then(/*...*/);
(编辑)如果我有多个不同环境常量的生产/开发配置?
假设你有像上面答案一样的API_URL
、API_URL_2
和API_URL_3
,它们应该支持不同的环境设置production/development/test
var API_URL = {
production: JSON.stringify('prod-url'),
development: JSON.stringify('dev-url')
};
var API_URL_2 = {
production: JSON.stringify('prod-url-2'),
development: JSON.stringify('dev-url-2'),
test: JSON.stringify('test-url-2')
};
var API_URL_3 = {
production: JSON.stringify('prod-url-3'),
development: JSON.stringify('dev-url-3'),
test: JSON.stringify('test-url-3')
};
// get available environment setting
var environment = function () {
switch(process.env.NODE_ENV) {
case 'production':
return 'production';
case 'development':
return 'development';
case 'test':
return 'test';
default: // in case ...
return 'production';
};
};
// default map for supported all production/development/test settings
var mapEnvToSettings = function (settingsConsts) {
return settingsConsts[environment()];
};
// special map for not supported all production/development/test settings
var mapAPI_URLtoSettings = function () {
switch(environment()) {
case 'production':
return API_URL.production;
case 'development':
return API_URL.development;
case 'test': // don't have special test case
return API_URL.development;
};
};
// webpack config
module.exports = {
// ...
plugins: [
new webpack.DefinePlugin({
'API_URL': mapAPI_URLtoSettings(),
'API_URL_2': mapEnvToSettings(API_URL_2),
'API_URL_3': mapEnvToSettings(API_URL_3)
})
],
// ...
}
(编辑2)
如果将字符串作为环境常量传递,则应该使用JSON.stringify
.
new webpack.DefinePlugin
的一个对象中完成此操作--它看起来更干净。发布于 2016-07-03 12:22:03
new webpack.DefinePlugin({
PRODUCTION: process.env.NODE_ENV === 'production'
})
然后,在您的代码中,您将编写类似以下内容:
var API_URL = PRODUCTION ? 'my-production-url' : 'my-development-url';
在编译过程中,webpack将用它的值替换PRODUCTION
(因此不是true
就是false
),这应该允许UglifyJS缩小我们的表达式:
var API_URL = <true/false> ? 'my-production-url' : 'my-development-url';
最糟糕的情况是,uglify无法缩小条件表达式,使其保持原样。
https://stackoverflow.com/questions/38164102
复制相似问题