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.

588 lines
15 KiB

3 months ago
  1. <div align="center">
  2. <a href="https://github.com/webpack/webpack">
  3. <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
  4. </a>
  5. </div>
  6. [![npm][npm]][npm-url]
  7. [![node][node]][node-url]
  8. [![deps][deps]][deps-url]
  9. [![tests][tests]][tests-url]
  10. [![cover][cover]][cover-url]
  11. [![chat][chat]][chat-url]
  12. [![size][size]][size-url]
  13. # css-minimizer-webpack-plugin
  14. This plugin uses [cssnano](https://cssnano.co) to optimize and minify your CSS.
  15. Just like [optimize-css-assets-webpack-plugin](https://github.com/NMFR/optimize-css-assets-webpack-plugin) but more accurate with source maps and assets using query string, allows caching and works in parallel mode.
  16. ## Getting Started
  17. To begin, you'll need to install `css-minimizer-webpack-plugin`:
  18. ```console
  19. $ npm install css-minimizer-webpack-plugin --save-dev
  20. ```
  21. Then add the plugin to your `webpack` configuration. For example:
  22. **webpack.config.js**
  23. ```js
  24. const MiniCssExtractPlugin = require("mini-css-extract-plugin");
  25. const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
  26. module.exports = {
  27. module: {
  28. rules: [
  29. {
  30. test: /.s?css$/,
  31. use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
  32. },
  33. ],
  34. },
  35. optimization: {
  36. minimizer: [
  37. // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
  38. // `...`,
  39. new CssMinimizerPlugin(),
  40. ],
  41. },
  42. plugins: [new MiniCssExtractPlugin()],
  43. };
  44. ```
  45. This will enable CSS optimization only in production mode.
  46. If you want to run it also in development set the `optimization.minimize` option to `true`:
  47. **webpack.config.js**
  48. ```js
  49. // [...]
  50. module.exports = {
  51. optimization: {
  52. // [...]
  53. minimize: true,
  54. },
  55. };
  56. ```
  57. And run `webpack` via your preferred method.
  58. ## Note about source maps
  59. **Works only with `source-map`, `inline-source-map`, `hidden-source-map` and `nosources-source-map` values for the [`devtool`](https://webpack.js.org/configuration/devtool/) option.**
  60. Why? Because CSS support only these source map types.
  61. The plugin respect the [`devtool`](https://webpack.js.org/configuration/devtool/) and using the `SourceMapDevToolPlugin` plugin.
  62. Using supported `devtool` values enable source map generation.
  63. Using `SourceMapDevToolPlugin` with enabled the `columns` option enables source map generation.
  64. Use source maps to map error message locations to modules (this slows down the compilation).
  65. If you use your own `minify` function please read the `minify` section for handling source maps correctly.
  66. ## Options
  67. | Name | Type | Default | Description |
  68. | :-----------------------------------------: | :--------------------------------------------: | :--------------------------------: | :---------------------------------------------------------------------- |
  69. | **[`test`](#test)** | `String\|RegExp\|Array<String\|RegExp>` | `/\.css(\?.*)?$/i` | Test to match files against. |
  70. | **[`include`](#include)** | `String\|RegExp\|Array<String\|RegExp>` | `undefined` | Files to include. |
  71. | **[`exclude`](#exclude)** | `String\|RegExp\|Array<String\|RegExp>` | `undefined` | Files to exclude. |
  72. | **[`parallel`](#parallel)** | `Boolean\|Number` | `true` | Enable/disable multi-process parallel running. |
  73. | **[`minify`](#minify)** | `Function\|Array<Function>` | `CssMinimizerPlugin.cssnanoMinify` | Allows to override default minify function. |
  74. | **[`minimizerOptions`](#minimizeroptions)** | `Object\|Array<Object>` | `{ preset: 'default' }` | Cssnano optimisations [options](https://cssnano.co/docs/optimisations). |
  75. | **[`warningsFilter`](#warningsfilter)** | `Function<(warning, file, source) -> Boolean>` | `() => true` | Allow to filter css-minimizer warnings. |
  76. ### `test`
  77. Type: `String|RegExp|Array<String|RegExp>` - default: `/\.css(\?.*)?$/i`
  78. Test to match files against.
  79. ```js
  80. module.exports = {
  81. optimization: {
  82. minimize: true,
  83. minimizer: [
  84. new CssMinimizerPlugin({
  85. test: /\.foo\.css$/i,
  86. }),
  87. ],
  88. },
  89. };
  90. ```
  91. ### `include`
  92. Type: `String|RegExp|Array<String|RegExp>`
  93. Default: `undefined`
  94. Files to include.
  95. **webpack.config.js**
  96. ```js
  97. module.exports = {
  98. optimization: {
  99. minimize: true,
  100. minimizer: [
  101. new CssMinimizerPlugin({
  102. include: /\/includes/,
  103. }),
  104. ],
  105. },
  106. };
  107. ```
  108. ### `exclude`
  109. Type: `String|RegExp|Array<String|RegExp>`
  110. Default: `undefined`
  111. Files to exclude.
  112. **webpack.config.js**
  113. ```js
  114. module.exports = {
  115. optimization: {
  116. minimize: true,
  117. minimizer: [
  118. new CssMinimizerPlugin({
  119. exclude: /\/excludes/,
  120. }),
  121. ],
  122. },
  123. };
  124. ```
  125. ### `parallel`
  126. Type: `Boolean|Number`
  127. Default: `true`
  128. Use multi-process parallel running to improve the build speed.
  129. Default number of concurrent runs: `os.cpus().length - 1`.
  130. > ℹ️ Parallelization can speed up your build significantly and is therefore **highly recommended**.
  131. > If a parallelization is enabled, the packages in `minimizerOptions` must be required via strings (`packageName` or `require.resolve(packageName)`). Read more in [`minimizerOptions`](#minimizeroptions)
  132. #### `Boolean`
  133. Enable/disable multi-process parallel running.
  134. **webpack.config.js**
  135. ```js
  136. module.exports = {
  137. optimization: {
  138. minimize: true,
  139. minimizer: [
  140. new CssMinimizerPlugin({
  141. parallel: true,
  142. }),
  143. ],
  144. },
  145. };
  146. ```
  147. #### `Number`
  148. Enable multi-process parallel running and set number of concurrent runs.
  149. **webpack.config.js**
  150. ```js
  151. module.exports = {
  152. optimization: {
  153. minimize: true,
  154. minimizer: [
  155. new CssMinimizerPlugin({
  156. parallel: 4,
  157. }),
  158. ],
  159. },
  160. };
  161. ```
  162. ### `minify`
  163. Type: `Function|Array<Function>`
  164. Default: `CssMinimizerPlugin.cssnanoMinify`
  165. Allows overriding default minify function.
  166. By default, plugin uses [cssnano](https://github.com/cssnano/cssnano) package.
  167. Useful for using and testing unpublished versions or forks.
  168. Possible options:
  169. - CssMinimizerPlugin.cssnanoMinify
  170. - CssMinimizerPlugin.cssoMinify
  171. - CssMinimizerPlugin.cleanCssMinify
  172. - CssMinimizerPlugin.esbuildMinify
  173. - CssMinimizerPlugin.parcelCssMinify
  174. - `async (data, inputMap, minimizerOptions) => {return {code: "a{color: red}", map: "...", warnings: [], errors: []}}`
  175. > ⚠️ **Always use `require` inside `minify` function when `parallel` option enabled**.
  176. #### `Function`
  177. **webpack.config.js**
  178. ```js
  179. module.exports = {
  180. optimization: {
  181. minimize: true,
  182. minimizer: [
  183. new CssMinimizerPlugin({
  184. minimizerOptions: {
  185. level: {
  186. 1: {
  187. roundingPrecision: "all=3,px=5",
  188. },
  189. },
  190. },
  191. minify: CssMinimizerPlugin.cleanCssMinify,
  192. }),
  193. ],
  194. },
  195. };
  196. ```
  197. #### `Array`
  198. If an array of functions is passed to the `minify` option, the `minimizerOptions` must also be an array.
  199. The function index in the `minify` array corresponds to the options object with the same index in the `minimizerOptions` array.
  200. **webpack.config.js**
  201. ```js
  202. module.exports = {
  203. optimization: {
  204. minimize: true,
  205. minimizer: [
  206. new CssMinimizerPlugin({
  207. minimizerOptions: [
  208. {}, // Options for the first function (CssMinimizerPlugin.cssnanoMinify)
  209. {}, // Options for the second function (CssMinimizerPlugin.cleanCssMinify)
  210. {}, // Options for the third function
  211. ],
  212. minify: [
  213. CssMinimizerPlugin.cssnanoMinify,
  214. CssMinimizerPlugin.cleanCssMinify,
  215. async (data, inputMap, minimizerOptions) => {
  216. // To do something
  217. return {
  218. code: `a{color: red}`,
  219. map: `{"version": "3", ...}`,
  220. warnings: [],
  221. errors: [],
  222. };
  223. },
  224. ],
  225. }),
  226. ],
  227. },
  228. };
  229. ```
  230. ### `minimizerOptions`
  231. Type: `Object|Array<Object>`
  232. Default: `{ preset: 'default' }`
  233. Cssnano optimisations [options](https://cssnano.co/docs/optimisations).
  234. #### `Object`
  235. ```js
  236. module.exports = {
  237. optimization: {
  238. minimize: true,
  239. minimizer: [
  240. new CssMinimizerPlugin({
  241. minimizerOptions: {
  242. preset: [
  243. "default",
  244. {
  245. discardComments: { removeAll: true },
  246. },
  247. ],
  248. },
  249. }),
  250. ],
  251. },
  252. };
  253. ```
  254. #### `Array`
  255. The function index in the `minify` array corresponds to the options object with the same index in the `minimizerOptions` array.
  256. If you use `minimizerOptions` like object, all `minify` function accept it.
  257. > If a parallelization is enabled, the packages in `minimizerOptions` must be required via strings (`packageName` or `require.resolve(packageName)`). In this case, we shouldn't use `require`/`import`.
  258. ```js
  259. module.exports = {
  260. optimization: {
  261. minimize: true,
  262. minimizer: [
  263. new CssMinimizerPlugin({
  264. minimizerOptions: {
  265. preset: require.resolve("cssnano-preset-simple"),
  266. },
  267. }),
  268. ],
  269. },
  270. };
  271. ```
  272. ##### `processorOptions` (⚠ only cssnano)
  273. Type: `Object`
  274. Default: `{ from: assetName }`
  275. Allows filtering options [`processoptions`](https://postcss.org/api/#processoptions) for the cssnano.
  276. The `parser`,` stringifier` and `syntax` can be either a function or a string indicating the module that will be imported.
  277. > ⚠️ **If a function is passed, the `parallel` option must be disabled.**.
  278. ```js
  279. import sugarss from "sugarss";
  280. module.exports = {
  281. optimization: {
  282. minimize: true,
  283. minimizer: [
  284. new CssMinimizerPlugin({
  285. parallel: false,
  286. minimizerOptions: {
  287. processorOptions: {
  288. parser: sugarss,
  289. },
  290. },
  291. }),
  292. ],
  293. },
  294. };
  295. ```
  296. ```js
  297. module.exports = {
  298. optimization: {
  299. minimize: true,
  300. minimizer: [
  301. new CssMinimizerPlugin({
  302. minimizerOptions: {
  303. processorOptions: {
  304. parser: "sugarss",
  305. },
  306. },
  307. }),
  308. ],
  309. },
  310. };
  311. ```
  312. ### `warningsFilter`
  313. Type: `Function<(warning, file, source) -> Boolean>`
  314. Default: `() => true`
  315. Allow filtering css-minimizer warnings (By default [cssnano](https://github.com/cssnano/cssnano)).
  316. Return `true` to keep the warning, a falsy value (`false`/`null`/`undefined`) otherwise.
  317. > ⚠️ The `source` argument will contain `undefined` if you don't use source maps.
  318. **webpack.config.js**
  319. ```js
  320. module.exports = {
  321. optimization: {
  322. minimize: true,
  323. minimizer: [
  324. new CssMinimizerPlugin({
  325. warningsFilter: (warning, file, source) => {
  326. if (/Dropping unreachable code/i.test(warning)) {
  327. return true;
  328. }
  329. if (/file\.css/i.test(file)) {
  330. return true;
  331. }
  332. if (/source\.css/i.test(source)) {
  333. return true;
  334. }
  335. return false;
  336. },
  337. }),
  338. ],
  339. },
  340. };
  341. ```
  342. ## Examples
  343. ### Use sourcemaps
  344. Don't forget to enable `sourceMap` options for all loaders.
  345. ```js
  346. const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
  347. module.exports = {
  348. devtool: "source-map",
  349. module: {
  350. rules: [
  351. {
  352. test: /.s?css$/,
  353. use: [
  354. MiniCssExtractPlugin.loader,
  355. { loader: "css-loader", options: { sourceMap: true } },
  356. { loader: "sass-loader", options: { sourceMap: true } },
  357. ],
  358. },
  359. ],
  360. },
  361. optimization: {
  362. minimizer: [new CssMinimizerPlugin()],
  363. },
  364. plugins: [new MiniCssExtractPlugin()],
  365. };
  366. ```
  367. ### Remove all comments
  368. Remove all comments (including comments starting with `/*!`).
  369. ```js
  370. module.exports = {
  371. optimization: {
  372. minimizer: [
  373. new CssMinimizerPlugin({
  374. minimizerOptions: {
  375. preset: [
  376. "default",
  377. {
  378. discardComments: { removeAll: true },
  379. },
  380. ],
  381. },
  382. }),
  383. ],
  384. },
  385. };
  386. ```
  387. ### Using custom minifier [csso](https://github.com/css/csso)
  388. **webpack.config.js**
  389. ```js
  390. module.exports = {
  391. // Uncomment if you need source maps
  392. // devtool: "source-map",
  393. optimization: {
  394. minimize: true,
  395. minimizer: [
  396. new CssMinimizerPlugin({
  397. minify: CssMinimizerPlugin.cssoMinify,
  398. // Uncomment this line for options
  399. // minimizerOptions: { restructure: false },
  400. }),
  401. ],
  402. },
  403. };
  404. ```
  405. ### Using custom minifier [clean-css](https://github.com/jakubpawlowicz/clean-css)
  406. **webpack.config.js**
  407. ```js
  408. module.exports = {
  409. // Uncomment if you need source maps
  410. // devtool: "source-map",
  411. optimization: {
  412. minimize: true,
  413. minimizer: [
  414. new CssMinimizerPlugin({
  415. minify: CssMinimizerPlugin.cleanCssMinify,
  416. // Uncomment this line for options
  417. // minimizerOptions: { compatibility: 'ie11,-properties.merging' },
  418. }),
  419. ],
  420. },
  421. };
  422. ```
  423. ### Using custom minifier [esbuild](https://github.com/evanw/esbuild)
  424. **webpack.config.js**
  425. ```js
  426. module.exports = {
  427. // Uncomment if you need source maps
  428. // devtool: "source-map",
  429. optimization: {
  430. minimize: true,
  431. minimizer: [
  432. new CssMinimizerPlugin({
  433. minify: CssMinimizerPlugin.esbuildMinify,
  434. }),
  435. ],
  436. },
  437. };
  438. ```
  439. ### Using custom minifier [@parcel/css](https://github.com/parcel-bundler/parcel-css)
  440. **webpack.config.js**
  441. ```js
  442. module.exports = {
  443. // Uncomment if you need source maps
  444. // devtool: "source-map",
  445. optimization: {
  446. minimize: true,
  447. minimizer: [
  448. new CssMinimizerPlugin({
  449. minify: CssMinimizerPlugin.parcelCssMinify,
  450. // Uncomment this line for options
  451. // minimizerOptions: { targets: { ie: 11 }, drafts: { nesting: true } },
  452. }),
  453. ],
  454. },
  455. };
  456. ```
  457. ## Contributing
  458. Please take a moment to read our contributing guidelines if you haven't yet done so.
  459. [CONTRIBUTING](./.github/CONTRIBUTING.md)
  460. ## License
  461. [MIT](./LICENSE)
  462. [npm]: https://img.shields.io/npm/v/css-minimizer-webpack-plugin.svg
  463. [npm-url]: https://npmjs.com/package/css-minimizer-webpack-plugin
  464. [node]: https://img.shields.io/node/v/css-minimizer-webpack-plugin.svg
  465. [node-url]: https://nodejs.org
  466. [deps]: https://david-dm.org/webpack-contrib/css-minimizer-webpack-plugin.svg
  467. [deps-url]: https://david-dm.org/webpack-contrib/css-minimizer-webpack-plugin
  468. [tests]: https://github.com/webpack-contrib/css-minimizer-webpack-plugin/workflows/css-minimizer-webpack-plugin/badge.svg
  469. [tests-url]: https://github.com/webpack-contrib/css-minimizer-webpack-plugin/actions
  470. [cover]: https://codecov.io/gh/webpack-contrib/css-minimizer-webpack-plugin/branch/master/graph/badge.svg
  471. [cover-url]: https://codecov.io/gh/webpack-contrib/css-minimizer-webpack-plugin
  472. [chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
  473. [chat-url]: https://gitter.im/webpack/webpack
  474. [size]: https://packagephobia.now.sh/badge?p=css-minimizer-webpack-plugin
  475. [size-url]: https://packagephobia.now.sh/result?p=css-minimizer-webpack-plugin