You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

314 lines
11 KiB

3 months ago
  1. [![Financial Contributors on Open Collective](https://opencollective.com/webpack-merge/all/badge.svg?label=financial+contributors)](https://opencollective.com/webpack-merge) [![Test](https://github.com/survivejs/webpack-merge/actions/workflows/test.yml/badge.svg?branch=develop&event=push)](https://github.com/survivejs/webpack-merge/actions/workflows/test.yml) [![codecov](https://codecov.io/gh/survivejs/webpack-merge/branch/master/graph/badge.svg)](https://codecov.io/gh/survivejs/webpack-merge)
  2. # webpack-merge - Merge designed for Webpack
  3. **webpack-merge** provides a `merge` function that concatenates arrays and merges objects creating a new object. If functions are encountered, it will execute them, run the results through the algorithm, and then wrap the returned values within a function again.
  4. This behavior is particularly useful in configuring webpack although it has uses beyond it. Whenever you need to merge configuration objects, **webpack-merge** can come in handy.
  5. ## **`merge(...configuration | [...configuration])`**
  6. `merge` is the core, and the most important idea, of the API. Often this is all you need unless you want further customization.
  7. ```javascript
  8. const { merge } = require('webpack-merge');
  9. // Default API
  10. const output = merge(object1, object2, object3, ...);
  11. // You can pass an array of objects directly.
  12. // This works with all available functions.
  13. const output = merge([object1, object2, object3]);
  14. // Keys matching to the right take precedence:
  15. const output = merge(
  16. { fruit: "apple", color: "red" },
  17. { fruit: "strawberries" }
  18. );
  19. console.log(output);
  20. // { color: "red", fruit: "strawberries"}
  21. ```
  22. ### Limitations
  23. Note that `Promise`s are not supported! If you want to return a configuration wrapped within a `Promise`, `merge` inside one. Example: `Promise.resolve(merge({ ... }, { ... }))`.
  24. The same goes for configuration level functions as in the example below:
  25. **webpack.config.js**
  26. ```javascript
  27. const commonConfig = { ... };
  28. const productionConfig = { ... };
  29. const developmentConfig = { ... };
  30. module.exports = (env, args) => {
  31. switch(args.mode) {
  32. case 'development':
  33. return merge(commonConfig, developmentConfig);
  34. case 'production':
  35. return merge(commonConfig, productionConfig);
  36. default:
  37. throw new Error('No matching configuration was found!');
  38. }
  39. }
  40. ```
  41. You can choose the configuration you want by using `webpack --mode development` assuming you are using _webpack-cli_.
  42. ## **`mergeWithCustomize({ customizeArray, customizeObject })(...configuration | [...configuration])`**
  43. In case you need more flexibility, `merge` behavior can be customized per field as below:
  44. ```javascript
  45. const { mergeWithCustomize } = require('webpack-merge');
  46. const output = mergeWithCustomize(
  47. {
  48. customizeArray(a, b, key) {
  49. if (key === 'extensions') {
  50. return _.uniq([...a, ...b]);
  51. }
  52. // Fall back to default merging
  53. return undefined;
  54. },
  55. customizeObject(a, b, key) {
  56. if (key === 'module') {
  57. // Custom merging
  58. return _.merge({}, a, b);
  59. }
  60. // Fall back to default merging
  61. return undefined;
  62. }
  63. }
  64. )(object1, object2, object3, ...);
  65. ```
  66. For example, if the previous code was invoked with only `object1` and `object2`
  67. with `object1` as:
  68. ```javascript
  69. {
  70. foo1: ['object1'],
  71. foo2: ['object1'],
  72. bar1: { object1: {} },
  73. bar2: { object1: {} },
  74. }
  75. ```
  76. and `object2` as:
  77. ```javascript
  78. {
  79. foo1: ['object2'],
  80. foo2: ['object2'],
  81. bar1: { object2: {} },
  82. bar2: { object2: {} },
  83. }
  84. ```
  85. then `customizeArray` will be invoked for each property of `Array` type, i.e:
  86. ```javascript
  87. customizeArray(["object1"], ["object2"], "foo1");
  88. customizeArray(["object1"], ["object2"], "foo2");
  89. ```
  90. and `customizeObject` will be invoked for each property of `Object` type, i.e:
  91. ```javascript
  92. customizeObject({ object1: {} }, { object2: {} }, bar1);
  93. customizeObject({ object1: {} }, { object2: {} }, bar2);
  94. ```
  95. ## **`customizeArray`** and **`customizeObject`**
  96. `customizeArray` and `customizeObject` provide small strategies to for `mergeWithCustomize`. They support `append`, `prepend`, `replace`, and wildcards for field names.
  97. ```javascript
  98. const { mergeWithCustomize, customizeArray, customizeObject } = require('webpack-merge');
  99. const output = mergeWithCustomize({
  100. customizeArray: customizeArray({
  101. 'entry.*': 'prepend'
  102. }),
  103. customizeObject: customizeObject({
  104. entry: 'prepend'
  105. })
  106. })(object1, object2, object3, ...);
  107. ```
  108. ## **`unique(<field>, <fields>, field => field)`**
  109. `unique` is a strategy used for forcing uniqueness within configuration. It's most useful with plugins when you want to make sure there's only one in place.
  110. The first `<field>` is the config property to look through for duplicates.
  111. `<fields>` represents the values that should be unique when you run the field => field function on each duplicate.
  112. When the order of elements of the `<field>` in the first configuration differs from the order in the second configuration, the latter is preserved.
  113. ```javascript
  114. const { mergeWithCustomize, unique } = require("webpack-merge");
  115. const output = mergeWithCustomize({
  116. customizeArray: unique(
  117. "plugins",
  118. ["HotModuleReplacementPlugin"],
  119. (plugin) => plugin.constructor && plugin.constructor.name
  120. ),
  121. })(
  122. {
  123. plugins: [new webpack.HotModuleReplacementPlugin()],
  124. },
  125. {
  126. plugins: [new webpack.HotModuleReplacementPlugin()],
  127. }
  128. );
  129. // Output contains only single HotModuleReplacementPlugin now and it's
  130. // going to be the last plugin instance.
  131. ```
  132. ## **`mergeWithRules`**
  133. To support advanced merging needs (i.e. merging within loaders), `mergeWithRules` includes additional syntax that allows you to match fields and apply strategies to match. Consider the full example below:
  134. ```javascript
  135. const a = {
  136. module: {
  137. rules: [
  138. {
  139. test: /\.css$/,
  140. use: [{ loader: "style-loader" }, { loader: "sass-loader" }],
  141. },
  142. ],
  143. },
  144. };
  145. const b = {
  146. module: {
  147. rules: [
  148. {
  149. test: /\.css$/,
  150. use: [
  151. {
  152. loader: "style-loader",
  153. options: {
  154. modules: true,
  155. },
  156. },
  157. ],
  158. },
  159. ],
  160. },
  161. };
  162. const result = {
  163. module: {
  164. rules: [
  165. {
  166. test: /\.css$/,
  167. use: [
  168. {
  169. loader: "style-loader",
  170. options: {
  171. modules: true,
  172. },
  173. },
  174. { loader: "sass-loader" },
  175. ],
  176. },
  177. ],
  178. },
  179. };
  180. assert.deepStrictEqual(
  181. mergeWithRules({
  182. module: {
  183. rules: {
  184. test: "match",
  185. use: {
  186. loader: "match",
  187. options: "replace",
  188. },
  189. },
  190. },
  191. })(a, b),
  192. result
  193. );
  194. ```
  195. The way it works is that you should annotate fields to match using `match` (or `CustomizeRule.Match` if you are using TypeScript) matching your configuration structure and then use specific strategies to define how particular fields should be transformed. If a match doesn't exist above a rule, then it will apply the rule automatically.
  196. **Supported annotations:**
  197. - `match` (`CustomizeRule.Match`) - Optional matcher that scopes merging behavior to a specific part based on similarity (think DOM or jQuery selectors)
  198. - `append` (`CustomizeRule.Append`) - Appends items
  199. - `prepend` (`CustomizeRule.Prepend`) - Prepends items
  200. - `replace` (`CustomizeRule.Replace`) - Replaces items
  201. - `merge` (`CustomizeRule.Merge`) - Merges objects (shallow merge)
  202. ## Using with TypeScript
  203. **webpack-merge** supports TypeScript out of the box. You should pass `Configuration` type from webpack to it as follows:
  204. ```typescript
  205. import { Configuration } from "webpack";
  206. import { merge } from "webpack-merge";
  207. const config = merge<Configuration>({...}, {...});
  208. ...
  209. ```
  210. ## Development
  211. 1. `nvm use`
  212. 1. `npm i`
  213. 1. `npm run build -- --watch` in one terminal
  214. 1. `npm t -- --watch` in another one
  215. Before contributing, please [open an issue](https://github.com/survivejs/webpack-merge/issues/new) where to discuss.
  216. ## Further Information and Support
  217. Check out [SurviveJS - Webpack 5](http://survivejs.com/) to dig deeper into webpack. The free book uses **webpack-merge** extensively and shows you how to compose your configuration to keep it maintainable.
  218. I am also available as a consultant in case you require specific assistance. I can contribute particularly in terms of improving maintainability of the setup while speeding it up and pointing out better practices. In addition to improving developer productivity, the work has impact on the end users of the product in terms of reduced application size and loading times.
  219. ## Contributors
  220. ### Code Contributors
  221. This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
  222. <a href="https://github.com/survivejs/webpack-merge/graphs/contributors"><img src="https://opencollective.com/webpack-merge/contributors.svg?width=890&button=false" /></a>
  223. ### Financial Contributors
  224. Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/webpack-merge/contribute)]
  225. #### Individuals
  226. <a href="https://opencollective.com/webpack-merge"><img src="https://opencollective.com/webpack-merge/individuals.svg?width=890"></a>
  227. #### Organizations
  228. Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/webpack-merge/contribute)]
  229. <a href="https://opencollective.com/webpack-merge/organization/0/website"><img src="https://opencollective.com/webpack-merge/organization/0/avatar.svg"></a>
  230. <a href="https://opencollective.com/webpack-merge/organization/1/website"><img src="https://opencollective.com/webpack-merge/organization/1/avatar.svg"></a>
  231. <a href="https://opencollective.com/webpack-merge/organization/2/website"><img src="https://opencollective.com/webpack-merge/organization/2/avatar.svg"></a>
  232. <a href="https://opencollective.com/webpack-merge/organization/3/website"><img src="https://opencollective.com/webpack-merge/organization/3/avatar.svg"></a>
  233. <a href="https://opencollective.com/webpack-merge/organization/4/website"><img src="https://opencollective.com/webpack-merge/organization/4/avatar.svg"></a>
  234. <a href="https://opencollective.com/webpack-merge/organization/5/website"><img src="https://opencollective.com/webpack-merge/organization/5/avatar.svg"></a>
  235. <a href="https://opencollective.com/webpack-merge/organization/6/website"><img src="https://opencollective.com/webpack-merge/organization/6/avatar.svg"></a>
  236. <a href="https://opencollective.com/webpack-merge/organization/7/website"><img src="https://opencollective.com/webpack-merge/organization/7/avatar.svg"></a>
  237. <a href="https://opencollective.com/webpack-merge/organization/8/website"><img src="https://opencollective.com/webpack-merge/organization/8/avatar.svg"></a>
  238. <a href="https://opencollective.com/webpack-merge/organization/9/website"><img src="https://opencollective.com/webpack-merge/organization/9/avatar.svg"></a>
  239. ## License
  240. **webpack-merge** is available under MIT. See LICENSE for more details.