codecamp

Webpack Configuration Types

除了导出单个配置外,还有一些能满足更多需求的使用方式。

导出函数

你可能会遇到需要区分开发环境和生产环境的情况。有很多种方式可以做到这一点。其中一种选择是由 webpack 配置导出一个函数而非对象,这个函数包含两个参数:

  • 参数一是环境(environment)。请查阅 environment 选项文档了解更多。
  • 参数二是传递给 webpack 的配置项,其中包含 ​output-path​ 和 ​mode​等。
-module.exports = {
+module.exports = function(env, argv) {
+  return {
+    mode: env.production ? 'production' : 'development',
+    devtool: env.production ? 'source-map' : 'eval',
     plugins: [
       new TerserPlugin({
         terserOptions: {
+          compress: argv.mode === 'production' // only if `--mode production` was passed
         }
       })
     ]
+  };
};

导出 Promise

当需要异步加载配置变量时,webpack 将执行函数并导出一个配置文件,同时返回一个 Promise。

module.exports = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        entry: './app.js',
        /* ... */
      });
    }, 5000);
  });
};

导出多种配置

除了导出单个配置对象/函数,你可能也会需要导出多种配置(webpack 3.1.0 起支持)。当运行 webpack 时,所有配置项都会构建。比如,对于多 targets(如 AMD 和 CommonJS)构建 library 时会非常有用。

module.exports = [
  {
    output: {
      filename: './dist-amd.js',
      libraryTarget: 'amd',
    },
    name: 'amd',
    entry: './app.js',
    mode: 'production',
  },
  {
    output: {
      filename: './dist-commonjs.js',
      libraryTarget: 'commonjs',
    },
    name: 'commonjs',
    entry: './app.js',
    mode: 'production',
  },
];

dependencies

以防你的某个配置依赖于另一个配置的输出,你可以使用一个 ​dependencies​ 列表指定一个依赖列表。

webpack.config.js

module.exports = [
  {
    name: 'client',
    target: 'web',
    // …
  },
  {
    name: 'server',
    target: 'node',
    dependencies: ['client'],
  },
];

parallelism

如果你导出了多个配置,你可以在配置中使用 ​parallelism​ 选项来指定编译的最大并发数。

  • 类型:​number
  • 支持版本:5.22.0+

webpack.config.js

module.exports = [
  {
    //config-1
  },
  {
    //config-2
  },
];
module.exports.parallelism = 1;


Webpack Configuration Languages
Webpack 入口和上下文
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }