通过webpack更改不同环境的硬编码URL常量

Wit*_*ult 29 javascript webpack webpack-dev-server

我有一个ApiCaller.js模块,它生成调用我们的api服务器来获取数据.它有const字段API_URL,它指向服务器url.此API_URL const针对devprod环境进行更改.

因此,当我需要部署到开发环境时,我需要手动更改该URL(API_URL)以指向dev-api-server,反之亦然.

我想在代码之外的这些配置参数,并在构建过程中我想动态更改它们,以便我可以使用不同的设置进行构建.

我正在使用webpack捆绑我的javascript,html,css文件.

Eve*_*tss 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]
        })
    ],
    // ...
}
Run Code Online (Sandbox Code Playgroud)

现在,您ApiCaller可以使用API_URL定义的变量,它将取决于以下变量process.env.NODE_ENV:

ajax(API_URL).then(/*...*/);
Run Code Online (Sandbox Code Playgroud)

(编辑)如果我有不同的环境常量的生产/开发配置?

试想一下,你API_URL喜欢在上面的回答,API_URL_2API_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)
        })
    ],
    // ...
}
Run Code Online (Sandbox Code Playgroud)

(编辑2)

  1. 如果您将字符串作为环境常量传递,则应使用JSON.stringify.
  2. 您不需要new webpack.DefinePlugin多次定义.你可以在一个传递给new webpack.DefinePlugin它的对象中做到- 它看起来更干净.