webpack-merge provides a merge function that concatenates arrays and merges objects creating a new object.

帮助文档不直观,所以,我们来测试一下,测试框架用jest,babel使用es5语法。

首先导入:

import { merge } from 'webpack-merge'

准则1:

test('有冲突后来者赢', () => {
   const output = merge(
      { fruit: "apple", color: "red" },
      { fruit: "strawberries" }
   )
   expect(output).toEqual({ fruit: 'strawberries', color: 'red' })
})

准则2:

test('无冲突嵌套合并', () => {
   let obj1 = {
      foo1: ['object1'],
      foo2: ['object1'],
      bar1: { object1: {} },
      bar2: { object1: {} },
   }

   let obj2 = {
      foo1: ['object2'],
      foo2: ['object2'],
      bar1: { object2: {} },
      bar2: { object2: {} },
   }

   const output = merge(obj1, obj2)

   expect(output).toEqual({
      foo1: ['object1', 'object2'],
      foo2: ['object1', 'object2'],
      bar1: { object1: {}, object2: {} },
      bar2: { object1: {}, object2: {} }
   })
})

清楚了函数的基本用法,我们将可以容易把配置分离到独立的模块,最后用merge将他们整合。