web 3d图形渲染器
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.

692 lines
17 KiB

  1. <div align="center">
  2. <img width="200" height="200" src="https://cdn.worldvectorlogo.com/logos/javascript.svg">
  3. <a href="https://webpack.js.org/">
  4. <img width="200" height="200" vspace="" hspace="25" src="https://cdn.rawgit.com/webpack/media/e7485eb2/logo/icon-square-big.svg">
  5. </a>
  6. <h1>mini-css-extract-plugin</h1>
  7. </div>
  8. [![npm][npm]][npm-url]
  9. [![node][node]][node-url]
  10. [![deps][deps]][deps-url]
  11. [![tests][tests]][tests-url]
  12. [![coverage][cover]][cover-url]
  13. [![chat][chat]][chat-url]
  14. [![size][size]][size-url]
  15. # mini-css-extract-plugin
  16. This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports On-Demand-Loading of CSS and SourceMaps.
  17. It builds on top of a new webpack v4 feature (module types) and requires webpack 4 to work.
  18. Compared to the extract-text-webpack-plugin:
  19. - Async loading
  20. - No duplicate compilation (performance)
  21. - Easier to use
  22. - Specific to CSS
  23. ## Getting Started
  24. To begin, you'll need to install `mini-css-extract-plugin`:
  25. ```bash
  26. npm install --save-dev mini-css-extract-plugin
  27. ```
  28. It's recommended to combine `mini-css-extract-plugin` with the [`css-loader`](https://github.com/webpack-contrib/css-loader)
  29. Then add the loader and the plugin to your `webpack` config. For example:
  30. **style.css**
  31. ```css
  32. body {
  33. background: green;
  34. }
  35. ```
  36. **component.js**
  37. ```js
  38. import './style.css';
  39. ```
  40. **webpack.config.js**
  41. ```js
  42. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  43. module.exports = {
  44. plugins: [new MiniCssExtractPlugin()],
  45. module: {
  46. rules: [
  47. {
  48. test: /\.css$/i,
  49. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  50. },
  51. ],
  52. },
  53. };
  54. ```
  55. ## Options
  56. ### `publicPath`
  57. Type: `String|Function`
  58. Default: the `publicPath` in `webpackOptions.output`
  59. Specifies a custom public path for the target file(s).
  60. #### `String`
  61. **webpack.config.js**
  62. ```js
  63. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  64. module.exports = {
  65. plugins: [
  66. new MiniCssExtractPlugin({
  67. // Options similar to the same options in webpackOptions.output
  68. // both options are optional
  69. filename: '[name].css',
  70. chunkFilename: '[id].css',
  71. }),
  72. ],
  73. module: {
  74. rules: [
  75. {
  76. test: /\.css$/,
  77. use: [
  78. {
  79. loader: MiniCssExtractPlugin.loader,
  80. options: {
  81. publicPath: '/public/path/to/',
  82. },
  83. },
  84. 'css-loader',
  85. ],
  86. },
  87. ],
  88. },
  89. };
  90. ```
  91. #### `Function`
  92. **webpack.config.js**
  93. ```js
  94. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  95. module.exports = {
  96. plugins: [
  97. new MiniCssExtractPlugin({
  98. // Options similar to the same options in webpackOptions.output
  99. // both options are optional
  100. filename: '[name].css',
  101. chunkFilename: '[id].css',
  102. }),
  103. ],
  104. module: {
  105. rules: [
  106. {
  107. test: /\.css$/,
  108. use: [
  109. {
  110. loader: MiniCssExtractPlugin.loader,
  111. options: {
  112. publicPath: (resourcePath, context) => {
  113. return path.relative(path.dirname(resourcePath), context) + '/';
  114. },
  115. },
  116. },
  117. 'css-loader',
  118. ],
  119. },
  120. ],
  121. },
  122. };
  123. ```
  124. ### `esModule`
  125. Type: `Boolean`
  126. Default: `false`
  127. By default, `mini-css-extract-plugin` generates JS modules that use the CommonJS modules syntax.
  128. There are some cases in which using ES modules is beneficial, like in the case of [module concatenation](https://webpack.js.org/plugins/module-concatenation-plugin/) and [tree shaking](https://webpack.js.org/guides/tree-shaking/).
  129. You can enable a ES module syntax using:
  130. **webpack.config.js**
  131. ```js
  132. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  133. module.exports = {
  134. plugins: [new MiniCssExtractPlugin()],
  135. module: {
  136. rules: [
  137. {
  138. test: /\.css$/i,
  139. use: [
  140. {
  141. loader: MiniCssExtractPlugin.loader,
  142. options: {
  143. esModule: true,
  144. },
  145. },
  146. 'css-loader',
  147. ],
  148. },
  149. ],
  150. },
  151. };
  152. ```
  153. ### `modules`
  154. Type: `Object`
  155. Default: `undefined`
  156. Configuration CSS Modules.
  157. #### `namedExport`
  158. Type: `Boolean`
  159. Default: `false`
  160. Enables/disables ES modules named export for locals.
  161. > ⚠ Names of locals are converted to `camelCase`.
  162. > ⚠ It is not allowed to use JavaScript reserved words in css class names.
  163. > ⚠ Options `esModule` and `modules.namedExport` in `css-loader` and `MiniCssExtractPlugin.loader` should be enabled.
  164. **styles.css**
  165. ```css
  166. .foo-baz {
  167. color: red;
  168. }
  169. .bar {
  170. color: blue;
  171. }
  172. ```
  173. **index.js**
  174. ```js
  175. import { fooBaz, bar } from './styles.css';
  176. console.log(fooBaz, bar);
  177. ```
  178. You can enable a ES module named export using:
  179. **webpack.config.js**
  180. ```js
  181. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  182. module.exports = {
  183. plugins: [new MiniCssExtractPlugin()],
  184. module: {
  185. rules: [
  186. {
  187. test: /\.css$/,
  188. use: [
  189. {
  190. loader: MiniCssExtractPlugin.loader,
  191. options: {
  192. esModule: true,
  193. modules: {
  194. namedExport: true,
  195. },
  196. },
  197. },
  198. {
  199. loader: 'css-loader',
  200. options: {
  201. esModule: true,
  202. modules: {
  203. namedExport: true,
  204. localIdentName: 'foo__[name]__[local]',
  205. },
  206. },
  207. },
  208. ],
  209. },
  210. ],
  211. },
  212. };
  213. ```
  214. ## Examples
  215. ### Minimal example
  216. **webpack.config.js**
  217. ```js
  218. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  219. module.exports = {
  220. plugins: [
  221. new MiniCssExtractPlugin({
  222. // Options similar to the same options in webpackOptions.output
  223. // all options are optional
  224. filename: '[name].css',
  225. chunkFilename: '[id].css',
  226. ignoreOrder: false, // Enable to remove warnings about conflicting order
  227. }),
  228. ],
  229. module: {
  230. rules: [
  231. {
  232. test: /\.css$/,
  233. use: [
  234. {
  235. loader: MiniCssExtractPlugin.loader,
  236. options: {
  237. // you can specify a publicPath here
  238. // by default it uses publicPath in webpackOptions.output
  239. publicPath: '../',
  240. hmr: process.env.NODE_ENV === 'development', // webpack 4 only
  241. },
  242. },
  243. 'css-loader',
  244. ],
  245. },
  246. ],
  247. },
  248. };
  249. ```
  250. ### The `publicPath` option as function
  251. **webpack.config.js**
  252. ```js
  253. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  254. module.exports = {
  255. plugins: [
  256. new MiniCssExtractPlugin({
  257. // Options similar to the same options in webpackOptions.output
  258. // both options are optional
  259. filename: '[name].css',
  260. chunkFilename: '[id].css',
  261. }),
  262. ],
  263. module: {
  264. rules: [
  265. {
  266. test: /\.css$/,
  267. use: [
  268. {
  269. loader: MiniCssExtractPlugin.loader,
  270. options: {
  271. publicPath: (resourcePath, context) => {
  272. // publicPath is the relative path of the resource to the context
  273. // e.g. for ./css/admin/main.css the publicPath will be ../../
  274. // while for ./css/main.css the publicPath will be ../
  275. return path.relative(path.dirname(resourcePath), context) + '/';
  276. },
  277. },
  278. },
  279. 'css-loader',
  280. ],
  281. },
  282. ],
  283. },
  284. };
  285. ```
  286. ### Advanced configuration example
  287. This plugin should be used only on `production` builds without `style-loader` in the loaders chain, especially if you want to have HMR in `development`.
  288. Here is an example to have both HMR in `development` and your styles extracted in a file for `production` builds.
  289. (Loaders options left out for clarity, adapt accordingly to your needs.)
  290. **webpack.config.js**
  291. ```js
  292. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  293. const devMode = process.env.NODE_ENV !== 'production';
  294. module.exports = {
  295. plugins: [
  296. new MiniCssExtractPlugin({
  297. // Options similar to the same options in webpackOptions.output
  298. // both options are optional
  299. filename: devMode ? '[name].css' : '[name].[hash].css',
  300. chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
  301. }),
  302. ],
  303. module: {
  304. rules: [
  305. {
  306. test: /\.(sa|sc|c)ss$/,
  307. use: [
  308. {
  309. loader: MiniCssExtractPlugin.loader,
  310. options: {
  311. hmr: process.env.NODE_ENV === 'development', // webpack 4 only
  312. },
  313. },
  314. 'css-loader',
  315. 'postcss-loader',
  316. 'sass-loader',
  317. ],
  318. },
  319. ],
  320. },
  321. };
  322. ```
  323. ### Hot Module Reloading (HMR)
  324. Note: HMR is automatically supported in webpack 5. No need to configure it. Skip the following:
  325. The `mini-css-extract-plugin` supports hot reloading of actual css files in development.
  326. Some options are provided to enable HMR of both standard stylesheets and locally scoped CSS or CSS modules.
  327. Below is an example configuration of mini-css for HMR use with CSS modules.
  328. While we attempt to hmr css-modules. It is not easy to perform when code-splitting with custom chunk names.
  329. `reloadAll` is an option that should only be enabled if HMR isn't working correctly.
  330. The core challenge with css-modules is that when code-split, the chunk ids can and do end up different compared to the filename.
  331. **webpack.config.js**
  332. ```js
  333. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  334. module.exports = {
  335. plugins: [
  336. new MiniCssExtractPlugin({
  337. // Options similar to the same options in webpackOptions.output
  338. // both options are optional
  339. filename: '[name].css',
  340. chunkFilename: '[id].css',
  341. }),
  342. ],
  343. module: {
  344. rules: [
  345. {
  346. test: /\.css$/,
  347. use: [
  348. {
  349. loader: MiniCssExtractPlugin.loader,
  350. options: {
  351. // only enable hot in development (webpack 4 only)
  352. hmr: process.env.NODE_ENV === 'development',
  353. // if hmr does not work, this is a forceful method.
  354. reloadAll: true,
  355. },
  356. },
  357. 'css-loader',
  358. ],
  359. },
  360. ],
  361. },
  362. };
  363. ```
  364. ### Minimizing For Production
  365. To minify the output, use a plugin like [optimize-css-assets-webpack-plugin](https://github.com/NMFR/optimize-css-assets-webpack-plugin).
  366. Setting `optimization.minimizer` overrides the defaults provided by webpack, so make sure to also specify a JS minimizer:
  367. **webpack.config.js**
  368. ```js
  369. const TerserJSPlugin = require('terser-webpack-plugin');
  370. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  371. const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
  372. module.exports = {
  373. optimization: {
  374. minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
  375. },
  376. plugins: [
  377. new MiniCssExtractPlugin({
  378. filename: '[name].css',
  379. chunkFilename: '[id].css',
  380. }),
  381. ],
  382. module: {
  383. rules: [
  384. {
  385. test: /\.css$/,
  386. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  387. },
  388. ],
  389. },
  390. };
  391. ```
  392. ### Using preloaded or inlined CSS
  393. The runtime code detects already added CSS via `<link>` or `<style>` tag.
  394. This can be useful when injecting CSS on server-side for Server-Side-Rendering.
  395. The `href` of the `<link>` tag has to match the URL that will be used for loading the CSS chunk.
  396. The `data-href` attribute can be used for `<link>` and `<style>` too.
  397. When inlining CSS `data-href` must be used.
  398. ### Extracting all CSS in a single file
  399. The CSS can be extracted in one CSS file using `optimization.splitChunks.cacheGroups`.
  400. **webpack.config.js**
  401. ```js
  402. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  403. module.exports = {
  404. optimization: {
  405. splitChunks: {
  406. cacheGroups: {
  407. styles: {
  408. name: 'styles',
  409. test: /\.css$/,
  410. chunks: 'all',
  411. enforce: true,
  412. },
  413. },
  414. },
  415. },
  416. plugins: [
  417. new MiniCssExtractPlugin({
  418. filename: '[name].css',
  419. }),
  420. ],
  421. module: {
  422. rules: [
  423. {
  424. test: /\.css$/,
  425. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  426. },
  427. ],
  428. },
  429. };
  430. ```
  431. ### Extracting CSS based on entry
  432. You may also extract the CSS based on the webpack entry name.
  433. This is especially useful if you import routes dynamically but want to keep your CSS bundled according to entry.
  434. This also prevents the CSS duplication issue one had with the ExtractTextPlugin.
  435. ```js
  436. const path = require('path');
  437. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  438. function recursiveIssuer(m) {
  439. if (m.issuer) {
  440. return recursiveIssuer(m.issuer);
  441. } else if (m.name) {
  442. return m.name;
  443. } else {
  444. return false;
  445. }
  446. }
  447. module.exports = {
  448. entry: {
  449. foo: path.resolve(__dirname, 'src/foo'),
  450. bar: path.resolve(__dirname, 'src/bar'),
  451. },
  452. optimization: {
  453. splitChunks: {
  454. cacheGroups: {
  455. fooStyles: {
  456. name: 'foo',
  457. test: (m, c, entry = 'foo') =>
  458. m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
  459. chunks: 'all',
  460. enforce: true,
  461. },
  462. barStyles: {
  463. name: 'bar',
  464. test: (m, c, entry = 'bar') =>
  465. m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
  466. chunks: 'all',
  467. enforce: true,
  468. },
  469. },
  470. },
  471. },
  472. plugins: [
  473. new MiniCssExtractPlugin({
  474. filename: '[name].css',
  475. }),
  476. ],
  477. module: {
  478. rules: [
  479. {
  480. test: /\.css$/,
  481. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  482. },
  483. ],
  484. },
  485. };
  486. ```
  487. ### Module Filename Option
  488. With the `moduleFilename` option you can use chunk data to customize the filename. This is particularly useful when dealing with multiple entry points and wanting to get more control out of the filename for a given entry point/chunk. In the example below, we'll use `moduleFilename` to output the generated css into a different directory.
  489. **webpack.config.js**
  490. ```js
  491. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  492. module.exports = {
  493. plugins: [
  494. new MiniCssExtractPlugin({
  495. moduleFilename: ({ name }) => `${name.replace('/js/', '/css/')}.css`,
  496. }),
  497. ],
  498. module: {
  499. rules: [
  500. {
  501. test: /\.css$/,
  502. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  503. },
  504. ],
  505. },
  506. };
  507. ```
  508. ### Long Term Caching
  509. For long term caching use `filename: "[contenthash].css"`. Optionally add `[name]`.
  510. **webpack.config.js**
  511. ```js
  512. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  513. module.exports = {
  514. plugins: [
  515. new MiniCssExtractPlugin({
  516. filename: '[name].[contenthash].css',
  517. chunkFilename: '[id].[contenthash].css',
  518. }),
  519. ],
  520. module: {
  521. rules: [
  522. {
  523. test: /\.css$/,
  524. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  525. },
  526. ],
  527. },
  528. };
  529. ```
  530. ### Remove Order Warnings
  531. For projects where css ordering has been mitigated through consistent use of scoping or naming conventions, the css order warnings can be disabled by setting the ignoreOrder flag to true for the plugin.
  532. **webpack.config.js**
  533. ```js
  534. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  535. module.exports = {
  536. plugins: [
  537. new MiniCssExtractPlugin({
  538. ignoreOrder: true,
  539. }),
  540. ],
  541. module: {
  542. rules: [
  543. {
  544. test: /\.css$/i,
  545. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  546. },
  547. ],
  548. },
  549. };
  550. ```
  551. ### Media Query Plugin
  552. If you'd like to extract the media queries from the extracted CSS (so mobile users don't need to load desktop or tablet specific CSS anymore) you should use one of the following plugins:
  553. - [Media Query Plugin](https://github.com/SassNinja/media-query-plugin)
  554. - [Media Query Splitting Plugin](https://github.com/mike-diamond/media-query-splitting-plugin)
  555. ## Contributing
  556. Please take a moment to read our contributing guidelines if you haven't yet done so.
  557. [CONTRIBUTING](./.github/CONTRIBUTING.md)
  558. ## License
  559. [MIT](./LICENSE)
  560. [npm]: https://img.shields.io/npm/v/mini-css-extract-plugin.svg
  561. [npm-url]: https://npmjs.com/package/mini-css-extract-plugin
  562. [node]: https://img.shields.io/node/v/mini-css-extract-plugin.svg
  563. [node-url]: https://nodejs.org
  564. [deps]: https://david-dm.org/webpack-contrib/mini-css-extract-plugin.svg
  565. [deps-url]: https://david-dm.org/webpack-contrib/mini-css-extract-plugin
  566. [tests]: https://github.com/webpack-contrib/mini-css-extract-plugin/workflows/mini-css-extract-plugin/badge.svg
  567. [tests-url]: https://github.com/webpack-contrib/mini-css-extract-plugin/actions
  568. [cover]: https://codecov.io/gh/webpack-contrib/mini-css-extract-plugin/branch/master/graph/badge.svg
  569. [cover-url]: https://codecov.io/gh/webpack-contrib/mini-css-extract-plugin
  570. [chat]: https://badges.gitter.im/webpack/webpack.svg
  571. [chat-url]: https://gitter.im/webpack/webpack
  572. [size]: https://packagephobia.now.sh/badge?p=mini-css-extract-plugin
  573. [size-url]: https://packagephobia.now.sh/result?p=mini-css-extract-plugin