我正在尝试将一个angular应用程序从gulp转换为webpack。在gulp中,我使用gulp预处理来替换html页面中的一些变量(例如数据库名称),这取决于NODE_ENV。用webpack实现类似结果的最佳方法是什么?


当前回答

我研究了几个关于如何设置特定于环境的变量的选项,最后得到了这样的结果:

我目前有2个webpack配置:

webpack.production.config.js

new webpack.DefinePlugin({
  'process.env':{
    'NODE_ENV': JSON.stringify('production'),
    'API_URL': JSON.stringify('http://localhost:8080/bands')
  }
}),

webpack.config.js

new webpack.DefinePlugin({
  'process.env':{
    'NODE_ENV': JSON.stringify('development'),
    'API_URL': JSON.stringify('http://10.10.10.10:8080/bands')
  }
}),

在我的代码中,我以这种(简要)方式获取API_URL的值:

统一文件格式

编辑2016年11月3日

Webpack文档有一个例子:https://webpack.js.org/plugins/define-plugin/#usage

new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true),
    VERSION: JSON.stringify("5fa3b9"),
    BROWSER_SUPPORTS_HTML5: true,
    TWO: "1+1",
    "typeof window": JSON.stringify("object")
})

使用ESLint,如果你有no-undef规则,你需要在代码中明确地允许未定义的变量。http://eslint.org/docs/rules/no-undef像这样:

/*global TWO*/
console.log('Running App version ' + TWO);

EDIT 2017年9月7日(Create-React-App特定)

如果您不喜欢配置太多,请查看Create-React-App: Create-React-App -添加自定义环境变量。实际上CRA使用Webpack。

其他回答

再给这些问题补充一个答案:

使用ExtendedDefinePlugin而不是DefinePlugin

npm install extended-define-webpack-plugin --save-dev.

ExtendedDefinePlugin使用起来更简单,并且有文档:-) 链接

因为DefinePlugin缺乏良好的文档,我想通过说它实际上像c#中的#DEFINE一样工作来帮助解决问题。

#if (DEBUG)
        Console.WriteLine("Debugging is enabled.");
#endif

因此,如果你想了解DefinePlugin是如何工作的,请阅读c# #define文档。链接

现在2020年,我也面临着同样的问题,但是对于这个老问题,有很多新的答案,就列举一些吧:

这是webpack.config.js

plugins: [
        new HtmlWebpackPlugin({
            // 1. title is the parameter, you can use in ejs template
            templateParameters:{
                title: JSON.stringify(someting: 'something'),
            },
        }), 


        //2. BUILT_AT is a parameter too. can use it.
        new webpack.DefinePlugin({
            BUILT_AT: webpack.DefinePlugin.runtimeValue(Date.now,"some"),

        }),

        //3. for webpack5, you can use global variable: __webpack_hash__
        //new webpack.ExtendedAPIPlugin()
    ],
    //4. this is not variable, this is module, so use 'import tt' to use it.
    externals: { 
        'ex_title': JSON.stringify({
            tt: 'eitentitle',
        })
    },

这4种方法只是基本的,我相信还有更多的方法。但我认为这是最简单的方法。

这里有一种方法,对我来说是有效的,并允许我通过重用json文件保持我的环境变量DRY。

const webpack = require('webpack');
let config = require('./settings.json');
if (__PROD__) {
    config = require('./settings-prod.json');
}

const envVars = {};
Object.keys(config).forEach((key) => {
    envVars[key] = JSON.stringify(config[key]);
});

new webpack.DefinePlugin({
    'process.env': envVars
}),

从Webpack v4开始,在Webpack配置中简单地设置模式就可以为你设置NODE_ENV(通过DefinePlugin)。文档。

只是另一个选项,如果你只想使用cli界面,只需使用webpack的define选项。我在包中添加了以下脚本。json:

"build-production": "webpack -p --define process.env.NODE_ENV='\"production\"' --progress --colors"

我只需要运行npm运行build-production。