专为 webpack 设计的 Merge
webpack-merge 提供了一个 merge 函数,它能够拼接数组并合并对象,从而创建一个新对象。如果遇到函数,它会执行这些函数,将结果通过算法处理,然后再将返回的值包装成一个新的函数。
这种行为在配置 webpack 时特别有用,尽管它的用途不仅限于此。每当你需要合并配置对象时,webpack-merge 都能派上用场。
merge(...configuration | [...configuration])merge 是 API 的核心,也是最重要的概念。通常,除非你需要进一步定制,否则这就是你所需要的全部。
const { merge } = require('webpack-merge');
// Default API
const output = merge(object1, object2, object3, ...);
// You can pass an array of objects directly.
// This works with all available functions.
const output = merge([object1, object2, object3]);
// Keys matching to the right take precedence:
const output = merge(
{ fruit: "apple", color: "red" },
{ fruit: "strawberries" }
);
console.log(output);
// { color: "red", fruit: "strawberries"}请注意,不支持 Promise!如果你想返回一个包裹在 Promise 中的配置,请在其中使用 merge。例如:Promise.resolve(merge({ ... }, { ... }))。
配置级别的函数也是如此,如下例所示:
webpack.config.js
const commonConfig = { ... };
const productionConfig = { ... };
const developmentConfig = { ... };
module.exports = (env, args) => {
switch(args.mode) {
case 'development':
return merge(commonConfig, developmentConfig);
case 'production':
return merge(commonConfig, productionConfig);
default:
throw new Error('No matching configuration was found!');
}
}假设你使用的是 webpack-cli,你可以通过 webpack --mode development 选择你想要的配置。
mergeWithCustomize({ customizeArray, customizeObject })(...configuration | [...configuration])*暂无开放 Issues,或尚未同步最近议题。