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


当前回答

现在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种方法只是基本的,我相信还有更多的方法。但我认为这是最简单的方法。

其他回答

我的webpack版本“webpack”:“^4.29.6”的变通方法非常简单。

//package.json
{
...
 "scripts": {
    "build": "webpack --mode production",
    "start": "webpack-dev-server --open --mode development"
  },
}

你可以在webpack命令中传递——mode参数,然后在webpack.config.js中

 // webpack.config.json
 module.exports = (env,argv) => {
        return {
           ...
           externals: {
            // global app config object
            config: JSON.stringify({
                apiUrl: (argv.mode==="production") ? '/api' : 'localhost:3002/api'
            })
        }
}

我在代码中像这样使用baseurl

// my api service
import config from 'config';
console.log(config.apiUrl) // like fetch(`${config.apiUrl}/users/user-login`)

现在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种方法只是基本的,我相信还有更多的方法。但我认为这是最简单的方法。

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

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

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

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

你可以直接使用webpack中的EnvironmentPlugin来在编译过程中访问任何环境变量。

你只需要在webpack.config.js文件中声明这个插件:

var webpack = require('webpack');

module.exports = {
    /* ... */
    plugins: [
        new webpack.EnvironmentPlugin(['NODE_ENV'])
    ]
};

注意,必须显式声明要使用的环境变量的名称。