我如何在webpack配置中获取模式,例如,用于推送某些插件。

package.json

"scripts": {
  "dev": "webpack --mode development",
  "build": "webpack --mode production"
}

我在webpack 3中所做的
package.json

"scripts": {
    "build": "cross-env NODE_ENV=development webpack",
    "prod": "cross-env NODE_ENV=production webpack"
  },

然后,我能够通过process.env.NODE_ENV在webpack中获取环境

当然,我可以通过NODE_ENV传递--mode,但是我希望避免重复。

最佳答案

您要避免重复传递给脚本的选项。

导出函数时,将使用2个参数调用该函数:环境作为第一个参数,选项映射作为第二个参数。

package.json

"scripts": {
  "build-dev": "webpack --mode development",
  "build-prod": "webpack --mode production"
},

webpack.config.js
module.exports = (env, options) => {
    console.log(`This is the Webpack 4 'mode': ${options.mode}`);
    return {
        ...
    };
}

结果如下:

对于npm run build-dev:
> webpack --mode development

This is the Webpack 4 'mode': development
Hash: 554dd20dff08600ad09b
Version: webpack 4.1.1
Time: 42ms
Built at: 2018-3-14 11:27:35

对于npm run build-prod:
> webpack --mode production

This is the Webpack 4 'mode': production
Hash: 8cc6c4e6b736eaa4183e
Version: webpack 4.1.1
Time: 42ms
Built at: 2018-3-14 11:28:32

09-25 21:07