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.

2066 lines
46 KiB

3 months ago
  1. <div align="center">
  2. <img width="180" height="180" vspace="20"
  3. src="https://cdn.worldvectorlogo.com/logos/css-3.svg">
  4. <a href="https://github.com/webpack/webpack">
  5. <img width="200" height="200"
  6. src="https://webpack.js.org/assets/icon-square-big.svg">
  7. </a>
  8. </div>
  9. [![npm][npm]][npm-url]
  10. [![node][node]][node-url]
  11. [![tests][tests]][tests-url]
  12. [![coverage][cover]][cover-url]
  13. [![discussion][discussion]][discussion-url]
  14. [![size][size]][size-url]
  15. # css-loader
  16. The `css-loader` interprets `@import` and `url()` like `import/require()` and will resolve them.
  17. ## Getting Started
  18. > **Warning**
  19. >
  20. > To use the latest version of css-loader, webpack@5 is required
  21. To begin, you'll need to install `css-loader`:
  22. ```console
  23. npm install --save-dev css-loader
  24. ```
  25. or
  26. ```console
  27. yarn add -D css-loader
  28. ```
  29. or
  30. ```console
  31. pnpm add -D css-loader
  32. ```
  33. Then add the plugin to your `webpack` config. For example:
  34. **file.js**
  35. ```js
  36. import css from "file.css";
  37. ```
  38. **webpack.config.js**
  39. ```js
  40. module.exports = {
  41. module: {
  42. rules: [
  43. {
  44. test: /\.css$/i,
  45. use: ["style-loader", "css-loader"],
  46. },
  47. ],
  48. },
  49. };
  50. ```
  51. And run `webpack` via your preferred method.
  52. If, for one reason or another, you need to extract CSS as a file (i.e. do not store CSS in a JS module) you might want to check out the [recommend example](https://github.com/webpack-contrib/css-loader#recommend).
  53. ## Options
  54. - **[`url`](#url)**
  55. - **[`import`](#import)**
  56. - **[`modules`](#modules)**
  57. - **[`sourceMap`](#sourcemap)**
  58. - **[`importLoaders`](#importloaders)**
  59. - **[`esModule`](#esmodule)**
  60. - **[`exportType`](#exporttype)**
  61. ### `url`
  62. Type:
  63. ```ts
  64. type url =
  65. | boolean
  66. | {
  67. filter: (url: string, resourcePath: string) => boolean;
  68. };
  69. ```
  70. Default: `true`
  71. Allow to enable/disables handling the CSS functions `url` and `image-set`.
  72. If set to `false`, `css-loader` will not parse any paths specified in `url` or `image-set`.
  73. A function can also be passed to control this behavior dynamically based on the path to the asset.
  74. Starting with version [4.0.0](https://github.com/webpack-contrib/css-loader/blob/master/CHANGELOG.md#400-2020-07-25), absolute paths are parsed based on the server root.
  75. Examples resolutions:
  76. ```js
  77. url(image.png) => require('./image.png')
  78. url('image.png') => require('./image.png')
  79. url(./image.png) => require('./image.png')
  80. url('./image.png') => require('./image.png')
  81. url('http://dontwritehorriblecode.com/2112.png') => require('http://dontwritehorriblecode.com/2112.png')
  82. image-set(url('image2x.png') 1x, url('image1x.png') 2x) => require('./image1x.png') and require('./image2x.png')
  83. ```
  84. To import assets from a `node_modules` path (include `resolve.modules`) and for `alias`, prefix it with a `~`:
  85. ```js
  86. url(~module/image.png) => require('module/image.png')
  87. url('~module/image.png') => require('module/image.png')
  88. url(~aliasDirectory/image.png) => require('otherDirectory/image.png')
  89. ```
  90. #### `boolean`
  91. Enable/disable `url()` resolving.
  92. **webpack.config.js**
  93. ```js
  94. module.exports = {
  95. module: {
  96. rules: [
  97. {
  98. test: /\.css$/i,
  99. loader: "css-loader",
  100. options: {
  101. url: true,
  102. },
  103. },
  104. ],
  105. },
  106. };
  107. ```
  108. #### `object`
  109. Allow to filter `url()`. All filtered `url()` will not be resolved (left in the code as they were written).
  110. **webpack.config.js**
  111. ```js
  112. module.exports = {
  113. module: {
  114. rules: [
  115. {
  116. test: /\.css$/i,
  117. loader: "css-loader",
  118. options: {
  119. url: {
  120. filter: (url, resourcePath) => {
  121. // resourcePath - path to css file
  122. // Don't handle `img.png` urls
  123. if (url.includes("img.png")) {
  124. return false;
  125. }
  126. // Don't handle images under root-relative /external_images/
  127. if (/^\/external_images\//.test(path)) {
  128. return false;
  129. }
  130. return true;
  131. },
  132. },
  133. },
  134. },
  135. ],
  136. },
  137. };
  138. ```
  139. ### `import`
  140. Type:
  141. <!-- use other name to prettify since import is reserved keyword -->
  142. ```ts
  143. type importFn =
  144. | boolean
  145. | {
  146. filter: (
  147. url: string,
  148. media: string,
  149. resourcePath: string,
  150. supports?: string,
  151. layer?: string
  152. ) => boolean;
  153. };
  154. ```
  155. Default: `true`
  156. Allows to enables/disables `@import` at-rules handling.
  157. Control `@import` resolving. Absolute urls in `@import` will be moved in runtime code.
  158. Examples resolutions:
  159. ```
  160. @import 'style.css' => require('./style.css')
  161. @import url(style.css) => require('./style.css')
  162. @import url('style.css') => require('./style.css')
  163. @import './style.css' => require('./style.css')
  164. @import url(./style.css) => require('./style.css')
  165. @import url('./style.css') => require('./style.css')
  166. @import url('http://dontwritehorriblecode.com/style.css') => @import url('http://dontwritehorriblecode.com/style.css') in runtime
  167. ```
  168. To import styles from a `node_modules` path (include `resolve.modules`) and for `alias`, prefix it with a `~`:
  169. ```
  170. @import url(~module/style.css) => require('module/style.css')
  171. @import url('~module/style.css') => require('module/style.css')
  172. @import url(~aliasDirectory/style.css) => require('otherDirectory/style.css')
  173. ```
  174. #### `boolean`
  175. Enable/disable `@import` resolving.
  176. **webpack.config.js**
  177. ```js
  178. module.exports = {
  179. module: {
  180. rules: [
  181. {
  182. test: /\.css$/i,
  183. loader: "css-loader",
  184. options: {
  185. import: true,
  186. },
  187. },
  188. ],
  189. },
  190. };
  191. ```
  192. #### `object`
  193. ##### `filter`
  194. Type:
  195. ```ts
  196. type filter = (url: string, media: string, resourcePath: string) => boolean;
  197. ```
  198. Default: `undefined`
  199. Allow to filter `@import`. All filtered `@import` will not be resolved (left in the code as they were written).
  200. **webpack.config.js**
  201. ```js
  202. module.exports = {
  203. module: {
  204. rules: [
  205. {
  206. test: /\.css$/i,
  207. loader: "css-loader",
  208. options: {
  209. import: {
  210. filter: (url, media, resourcePath) => {
  211. // resourcePath - path to css file
  212. // Don't handle `style.css` import
  213. if (url.includes("style.css")) {
  214. return false;
  215. }
  216. return true;
  217. },
  218. },
  219. },
  220. },
  221. ],
  222. },
  223. };
  224. ```
  225. ### `modules`
  226. Type:
  227. ```ts
  228. type modules =
  229. | boolean
  230. | "local"
  231. | "global"
  232. | "pure"
  233. | "icss"
  234. | {
  235. auto: boolean | regExp | ((resourcePath: string) => boolean);
  236. mode:
  237. | "local"
  238. | "global"
  239. | "pure"
  240. | "icss"
  241. | ((resourcePath) => "local" | "global" | "pure" | "icss");
  242. localIdentName: string;
  243. localIdentContext: string;
  244. localIdentHashSalt: string;
  245. localIdentHashFunction: string;
  246. localIdentHashDigest: string;
  247. localIdentRegExp: string | regExp;
  248. getLocalIdent: (
  249. context: LoaderContext,
  250. localIdentName: string,
  251. localName: string
  252. ) => string;
  253. namedExport: boolean;
  254. exportGlobals: boolean;
  255. exportLocalsConvention:
  256. | "asIs"
  257. | "camelCase"
  258. | "camelCaseOnly"
  259. | "dashes"
  260. | "dashesOnly"
  261. | ((name: string) => string);
  262. exportOnlyLocals: boolean;
  263. };
  264. ```
  265. Default: `undefined`
  266. Allows to enable/disable CSS Modules or ICSS and setup configuration:
  267. - `undefined` - enable CSS modules for all files matching `/\.module\.\w+$/i.test(filename)` and `/\.icss\.\w+$/i.test(filename)` regexp.
  268. - `true` - enable CSS modules for all files.
  269. - `false` - disables CSS Modules for all files.
  270. - `string` - disables CSS Modules for all files and set the `mode` option, more information you can read [here](https://github.com/webpack-contrib/css-loader#mode)
  271. - `object` - enable CSS modules for all files, if `modules.auto` option is not specified, otherwise the `modules.auto` option will determine whether if it is CSS modules or not, more information you can read [here](https://github.com/webpack-contrib/css-loader#auto)
  272. The `modules` option enables/disables the **[CSS Modules](https://github.com/css-modules/css-modules)** specification and setup basic behaviour.
  273. Using `false` value increase performance because we avoid parsing **CSS Modules** features, it will be useful for developers who use vanilla css or use other technologies.
  274. **webpack.config.js**
  275. ```js
  276. module.exports = {
  277. module: {
  278. rules: [
  279. {
  280. test: /\.css$/i,
  281. loader: "css-loader",
  282. options: {
  283. modules: true,
  284. },
  285. },
  286. ],
  287. },
  288. };
  289. ```
  290. #### `Features`
  291. ##### `Scope`
  292. Using `local` value requires you to specify `:global` classes.
  293. Using `global` value requires you to specify `:local` classes.
  294. Using `pure` value requires selectors must contain at least one local class or id.
  295. You can find more information [here](https://github.com/css-modules/css-modules).
  296. Styles can be locally scoped to avoid globally scoping styles.
  297. The syntax `:local(.className)` can be used to declare `className` in the local scope. The local identifiers are exported by the module.
  298. With `:local` (without brackets) local mode can be switched on for this selector.
  299. The `:global(.className)` notation can be used to declare an explicit global selector.
  300. With `:global` (without brackets) global mode can be switched on for this selector.
  301. The loader replaces local selectors with unique identifiers. The chosen unique identifiers are exported by the module.
  302. ```css
  303. :local(.className) {
  304. background: red;
  305. }
  306. :local .className {
  307. color: green;
  308. }
  309. :local(.className .subClass) {
  310. color: green;
  311. }
  312. :local .className .subClass :global(.global-class-name) {
  313. color: blue;
  314. }
  315. ```
  316. ```css
  317. ._23_aKvs-b8bW2Vg3fwHozO {
  318. background: red;
  319. }
  320. ._23_aKvs-b8bW2Vg3fwHozO {
  321. color: green;
  322. }
  323. ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 {
  324. color: green;
  325. }
  326. ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name {
  327. color: blue;
  328. }
  329. ```
  330. > **Note**
  331. >
  332. > Identifiers are exported
  333. ```js
  334. exports.locals = {
  335. className: "_23_aKvs-b8bW2Vg3fwHozO",
  336. subClass: "_13LGdX8RMStbBE9w-t0gZ1",
  337. };
  338. ```
  339. CamelCase is recommended for local selectors. They are easier to use within the imported JS module.
  340. You can use `:local(#someId)`, but this is not recommended. Use classes instead of ids.
  341. ##### `Composing`
  342. When declaring a local classname you can compose a local class from another local classname.
  343. ```css
  344. :local(.className) {
  345. background: red;
  346. color: yellow;
  347. }
  348. :local(.subClass) {
  349. composes: className;
  350. background: blue;
  351. }
  352. ```
  353. This doesn't result in any change to the CSS itself but exports multiple classnames.
  354. ```js
  355. exports.locals = {
  356. className: "_23_aKvs-b8bW2Vg3fwHozO",
  357. subClass: "_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO",
  358. };
  359. ```
  360. ```css
  361. ._23_aKvs-b8bW2Vg3fwHozO {
  362. background: red;
  363. color: yellow;
  364. }
  365. ._13LGdX8RMStbBE9w-t0gZ1 {
  366. background: blue;
  367. }
  368. ```
  369. ##### `Importing`
  370. To import a local classname from another module.
  371. > **Note**
  372. >
  373. > We strongly recommend that you specify the extension when importing a file, since it is possible to import a file with any extension and it is not known in advance which file to use.
  374. ```css
  375. :local(.continueButton) {
  376. composes: button from "library/button.css";
  377. background: red;
  378. }
  379. ```
  380. ```css
  381. :local(.nameEdit) {
  382. composes: edit highlight from "./edit.css";
  383. background: red;
  384. }
  385. ```
  386. To import from multiple modules use multiple `composes:` rules.
  387. ```css
  388. :local(.className) {
  389. composes: edit highlight from "./edit.css", button from "module/button.css", classFromThisModule;
  390. background: red;
  391. }
  392. ```
  393. or
  394. ```css
  395. :local(.className) {
  396. composes: edit highlight from "./edit.css";
  397. composes: button from "module/button.css";
  398. composes: classFromThisModule;
  399. background: red;
  400. }
  401. ```
  402. ##### `Values`
  403. You can use `@value` to specific values to be reused throughout a document.
  404. We recommend use prefix `v-` for values, `s-` for selectors and `m-` for media at-rules.
  405. ```css
  406. @value v-primary: #BF4040;
  407. @value s-black: black-selector;
  408. @value m-large: (min-width: 960px);
  409. .header {
  410. color: v-primary;
  411. padding: 0 10px;
  412. }
  413. .s-black {
  414. color: black;
  415. }
  416. @media m-large {
  417. .header {
  418. padding: 0 20px;
  419. }
  420. }
  421. ```
  422. #### `boolean`
  423. Enable **CSS Modules** features.
  424. **webpack.config.js**
  425. ```js
  426. module.exports = {
  427. module: {
  428. rules: [
  429. {
  430. test: /\.css$/i,
  431. loader: "css-loader",
  432. options: {
  433. modules: true,
  434. },
  435. },
  436. ],
  437. },
  438. };
  439. ```
  440. #### `string`
  441. Enable **CSS Modules** features and setup `mode`.
  442. **webpack.config.js**
  443. ```js
  444. module.exports = {
  445. module: {
  446. rules: [
  447. {
  448. test: /\.css$/i,
  449. loader: "css-loader",
  450. options: {
  451. // Using `local` value has same effect like using `modules: true`
  452. modules: "global",
  453. },
  454. },
  455. ],
  456. },
  457. };
  458. ```
  459. #### `object`
  460. Enable **CSS Modules** features and setup options for them.
  461. **webpack.config.js**
  462. ```js
  463. module.exports = {
  464. module: {
  465. rules: [
  466. {
  467. test: /\.css$/i,
  468. loader: "css-loader",
  469. options: {
  470. modules: {
  471. mode: "local",
  472. auto: true,
  473. exportGlobals: true,
  474. localIdentName: "[path][name]__[local]--[hash:base64:5]",
  475. localIdentContext: path.resolve(__dirname, "src"),
  476. localIdentHashSalt: "my-custom-hash",
  477. namedExport: true,
  478. exportLocalsConvention: "camelCase",
  479. exportOnlyLocals: false,
  480. },
  481. },
  482. },
  483. ],
  484. },
  485. };
  486. ```
  487. ##### `auto`
  488. Type:
  489. ```ts
  490. type auto =
  491. | boolean
  492. | regExp
  493. | ((
  494. resourcePath: string,
  495. resourceQuery: string,
  496. resourceFragment: string
  497. ) => boolean);
  498. ```
  499. Default: `undefined`
  500. Allows auto enable CSS modules/ICSS based on the filename, query or fragment when `modules` option is object.
  501. Possible values:
  502. - `undefined` - enable CSS modules for all files.
  503. - `true` - enable CSS modules for all files matching `/\.module\.\w+$/i.test(filename)` and `/\.icss\.\w+$/i.test(filename)` regexp.
  504. - `false` - disables CSS Modules.
  505. - `RegExp` - enable CSS modules for all files matching `/RegExp/i.test(filename)` regexp.
  506. - `function` - enable CSS Modules for files based on the filename satisfying your filter function check.
  507. ###### `boolean`
  508. Possible values:
  509. - `true` - enables CSS modules or interoperable CSS format, sets the [`modules.mode`](#mode) option to `local` value for all files which satisfy `/\.module(s)?\.\w+$/i.test(filename)` condition or sets the [`modules.mode`](#mode) option to `icss` value for all files which satisfy `/\.icss\.\w+$/i.test(filename)` condition
  510. - `false` - disables CSS modules or interoperable CSS format based on filename
  511. **webpack.config.js**
  512. ```js
  513. module.exports = {
  514. module: {
  515. rules: [
  516. {
  517. test: /\.css$/i,
  518. loader: "css-loader",
  519. options: {
  520. modules: {
  521. auto: true,
  522. },
  523. },
  524. },
  525. ],
  526. },
  527. };
  528. ```
  529. ###### `RegExp`
  530. Enable CSS modules for files based on the filename satisfying your regex check.
  531. **webpack.config.js**
  532. ```js
  533. module.exports = {
  534. module: {
  535. rules: [
  536. {
  537. test: /\.css$/i,
  538. loader: "css-loader",
  539. options: {
  540. modules: {
  541. auto: /\.custom-module\.\w+$/i,
  542. },
  543. },
  544. },
  545. ],
  546. },
  547. };
  548. ```
  549. ###### `function`
  550. Enable CSS modules for files based on the filename, query or fragment satisfying your filter function check.
  551. **webpack.config.js**
  552. ```js
  553. module.exports = {
  554. module: {
  555. rules: [
  556. {
  557. test: /\.css$/i,
  558. loader: "css-loader",
  559. options: {
  560. modules: {
  561. auto: (resourcePath, resourceQuery, resourceFragment) => {
  562. return resourcePath.endsWith(".custom-module.css");
  563. },
  564. },
  565. },
  566. },
  567. ],
  568. },
  569. };
  570. ```
  571. ##### `mode`
  572. Type:
  573. ```ts
  574. type mode =
  575. | "local"
  576. | "global"
  577. | "pure"
  578. | "icss"
  579. | ((
  580. resourcePath: string,
  581. resourceQuery: string,
  582. resourceFragment: string
  583. ) => "local" | "global" | "pure" | "icss");
  584. ```
  585. Default: `'local'`
  586. Setup `mode` option. You can omit the value when you want `local` mode.
  587. Controls the level of compilation applied to the input styles.
  588. The `local`, `global`, and `pure` handles `class` and `id` scoping and `@value` values.
  589. The `icss` will only compile the low level `Interoperable CSS` format for declaring `:import` and `:export` dependencies between CSS and other languages.
  590. ICSS underpins CSS Module support, and provides a low level syntax for other tools to implement CSS-module variations of their own.
  591. ###### `string`
  592. Possible values - `local`, `global`, `pure`, and `icss`.
  593. **webpack.config.js**
  594. ```js
  595. module.exports = {
  596. module: {
  597. rules: [
  598. {
  599. test: /\.css$/i,
  600. loader: "css-loader",
  601. options: {
  602. modules: {
  603. mode: "global",
  604. },
  605. },
  606. },
  607. ],
  608. },
  609. };
  610. ```
  611. ###### `function`
  612. Allows set different values for the `mode` option based on the filename, query or fragment.
  613. Possible return values - `local`, `global`, `pure` and `icss`.
  614. **webpack.config.js**
  615. ```js
  616. module.exports = {
  617. module: {
  618. rules: [
  619. {
  620. test: /\.css$/i,
  621. loader: "css-loader",
  622. options: {
  623. modules: {
  624. // Callback must return "local", "global", or "pure" values
  625. mode: (resourcePath, resourceQuery, resourceFragment) => {
  626. if (/pure.css$/i.test(resourcePath)) {
  627. return "pure";
  628. }
  629. if (/global.css$/i.test(resourcePath)) {
  630. return "global";
  631. }
  632. return "local";
  633. },
  634. },
  635. },
  636. },
  637. ],
  638. },
  639. };
  640. ```
  641. ##### `localIdentName`
  642. Type:
  643. ```ts
  644. type localIdentName = string;
  645. ```
  646. Default: `'[hash:base64]'`
  647. Allows to configure the generated local ident name.
  648. For more information on options see:
  649. - [webpack template strings](https://webpack.js.org/configuration/output/#template-strings),
  650. - [output.hashDigest](https://webpack.js.org/configuration/output/#outputhashdigest),
  651. - [output.hashDigestLength](https://webpack.js.org/configuration/output/#outputhashdigestlength),
  652. - [output.hashFunction](https://webpack.js.org/configuration/output/#outputhashfunction),
  653. - [output.hashSalt](https://webpack.js.org/configuration/output/#outputhashsalt).
  654. Supported template strings:
  655. - `[name]` the basename of the resource
  656. - `[folder]` the folder the resource relative to the `compiler.context` option or `modules.localIdentContext` option.
  657. - `[path]` the path of the resource relative to the `compiler.context` option or `modules.localIdentContext` option.
  658. - `[file]` - filename and path.
  659. - `[ext]` - extension with leading `.`.
  660. - `[hash]` - the hash of the string, generated based on `localIdentHashSalt`, `localIdentHashFunction`, `localIdentHashDigest`, `localIdentHashDigestLength`, `localIdentContext`, `resourcePath` and `exportName`
  661. - `[<hashFunction>:hash:<hashDigest>:<hashDigestLength>]` - hash with hash settings.
  662. - `[local]` - original class.
  663. Recommendations:
  664. - use `'[path][name]__[local]'` for development
  665. - use `'[hash:base64]'` for production
  666. The `[local]` placeholder contains original class.
  667. **Note:** all reserved (`<>:"/\|?*`) and control filesystem characters (excluding characters in the `[local]` placeholder) will be converted to `-`.
  668. **webpack.config.js**
  669. ```js
  670. module.exports = {
  671. module: {
  672. rules: [
  673. {
  674. test: /\.css$/i,
  675. loader: "css-loader",
  676. options: {
  677. modules: {
  678. localIdentName: "[path][name]__[local]--[hash:base64:5]",
  679. },
  680. },
  681. },
  682. ],
  683. },
  684. };
  685. ```
  686. ##### `localIdentContext`
  687. Type:
  688. ```ts
  689. type localIdentContex = string;
  690. ```
  691. Default: `compiler.context`
  692. Allows to redefine basic loader context for local ident name.
  693. **webpack.config.js**
  694. ```js
  695. module.exports = {
  696. module: {
  697. rules: [
  698. {
  699. test: /\.css$/i,
  700. loader: "css-loader",
  701. options: {
  702. modules: {
  703. localIdentContext: path.resolve(__dirname, "src"),
  704. },
  705. },
  706. },
  707. ],
  708. },
  709. };
  710. ```
  711. ##### `localIdentHashSalt`
  712. Type:
  713. ```ts
  714. type localIdentHashSalt = string;
  715. ```
  716. Default: `undefined`
  717. Allows to add custom hash to generate more unique classes.
  718. For more information see [output.hashSalt](https://webpack.js.org/configuration/output/#outputhashsalt).
  719. **webpack.config.js**
  720. ```js
  721. module.exports = {
  722. module: {
  723. rules: [
  724. {
  725. test: /\.css$/i,
  726. loader: "css-loader",
  727. options: {
  728. modules: {
  729. localIdentHashSalt: "hash",
  730. },
  731. },
  732. },
  733. ],
  734. },
  735. };
  736. ```
  737. ##### `localIdentHashFunction`
  738. Type:
  739. ```ts
  740. type localIdentHashFunction = string;
  741. ```
  742. Default: `md4`
  743. Allows to specify hash function to generate classes .
  744. For more information see [output.hashFunction](https://webpack.js.org/configuration/output/#outputhashfunction).
  745. **webpack.config.js**
  746. ```js
  747. module.exports = {
  748. module: {
  749. rules: [
  750. {
  751. test: /\.css$/i,
  752. loader: "css-loader",
  753. options: {
  754. modules: {
  755. localIdentHashFunction: "md4",
  756. },
  757. },
  758. },
  759. ],
  760. },
  761. };
  762. ```
  763. ##### `localIdentHashDigest`
  764. Type:
  765. ```ts
  766. type localIdentHashDigest = string;
  767. ```
  768. Default: `hex`
  769. Allows to specify hash digest to generate classes.
  770. For more information see [output.hashDigest](https://webpack.js.org/configuration/output/#outputhashdigest).
  771. **webpack.config.js**
  772. ```js
  773. module.exports = {
  774. module: {
  775. rules: [
  776. {
  777. test: /\.css$/i,
  778. loader: "css-loader",
  779. options: {
  780. modules: {
  781. localIdentHashDigest: "base64",
  782. },
  783. },
  784. },
  785. ],
  786. },
  787. };
  788. ```
  789. ##### `localIdentHashDigestLength`
  790. Type:
  791. ```ts
  792. type localIdentHashDigestLength = number;
  793. ```
  794. Default: `20`
  795. Allows to specify hash digest length to generate classes.
  796. For more information see [output.hashDigestLength](https://webpack.js.org/configuration/output/#outputhashdigestlength).
  797. **webpack.config.js**
  798. ```js
  799. module.exports = {
  800. module: {
  801. rules: [
  802. {
  803. test: /\.css$/i,
  804. loader: "css-loader",
  805. options: {
  806. modules: {
  807. localIdentHashDigestLength: 5,
  808. },
  809. },
  810. },
  811. ],
  812. },
  813. };
  814. ```
  815. ##### `hashStrategy`
  816. Type: `'resource-path-and-local-name' | 'minimal-subset'`
  817. Default: `'resource-path-and-local-name'`
  818. Should local name be used when computing the hash.
  819. - `'resource-path-and-local-name'` Both resource path and local name are used when hashing. Each identifier in a module gets its own hash digest, always.
  820. - `'minimal-subset'` Auto detect if identifier names can be omitted from hashing. Use this value to optimize the output for better GZIP or Brotli compression.
  821. **webpack.config.js**
  822. ```js
  823. module.exports = {
  824. module: {
  825. rules: [
  826. {
  827. test: /\.css$/i,
  828. loader: "css-loader",
  829. options: {
  830. modules: {
  831. hashStrategy: "minimal-subset",
  832. },
  833. },
  834. },
  835. ],
  836. },
  837. };
  838. ```
  839. ##### `localIdentRegExp`
  840. Type:
  841. ```ts
  842. type localIdentRegExp = string | RegExp;
  843. ```
  844. Default: `undefined`
  845. **webpack.config.js**
  846. ```js
  847. module.exports = {
  848. module: {
  849. rules: [
  850. {
  851. test: /\.css$/i,
  852. loader: "css-loader",
  853. options: {
  854. modules: {
  855. localIdentRegExp: /page-(.*)\.css/i,
  856. },
  857. },
  858. },
  859. ],
  860. },
  861. };
  862. ```
  863. ##### `getLocalIdent`
  864. Type:
  865. ```ts
  866. type getLocalIdent = (
  867. context: LoaderContext,
  868. localIdentName: string,
  869. localName: string
  870. ) => string;
  871. ```
  872. Default: `undefined`
  873. Allows to specify a function to generate the classname.
  874. By default we use built-in function to generate a classname.
  875. If the custom function returns `null` or `undefined`, we fallback to the
  876. built-in function to generate the classname.
  877. **webpack.config.js**
  878. ```js
  879. module.exports = {
  880. module: {
  881. rules: [
  882. {
  883. test: /\.css$/i,
  884. loader: "css-loader",
  885. options: {
  886. modules: {
  887. getLocalIdent: (context, localIdentName, localName, options) => {
  888. return "whatever_random_class_name";
  889. },
  890. },
  891. },
  892. },
  893. ],
  894. },
  895. };
  896. ```
  897. ##### `namedExport`
  898. Type:
  899. ```ts
  900. type namedExport = boolean;
  901. ```
  902. Default: `false`
  903. Enables/disables ES modules named export for locals.
  904. > **Warning**
  905. >
  906. > Names of locals are converted to camelcase, i.e. the `exportLocalsConvention` option has
  907. > `camelCaseOnly` value by default. You can set this back to any other valid option but selectors
  908. > which are not valid JavaScript identifiers may run into problems which do not implement the entire
  909. > modules specification.
  910. > **Warning**
  911. >
  912. > It is not allowed to use JavaScript reserved words in css class names unless
  913. > `exportLocalsConvention` is `"asIs"`.
  914. **styles.css**
  915. ```css
  916. .foo-baz {
  917. color: red;
  918. }
  919. .bar {
  920. color: blue;
  921. }
  922. ```
  923. **index.js**
  924. ```js
  925. import * as styles from "./styles.css";
  926. console.log(styles.fooBaz, styles.bar);
  927. // or if using `exportLocalsConvention: "asIs"`:
  928. console.log(styles["foo-baz"], styles.bar);
  929. ```
  930. You can enable a ES module named export using:
  931. **webpack.config.js**
  932. ```js
  933. module.exports = {
  934. module: {
  935. rules: [
  936. {
  937. test: /\.css$/i,
  938. loader: "css-loader",
  939. options: {
  940. esModule: true,
  941. modules: {
  942. namedExport: true,
  943. },
  944. },
  945. },
  946. ],
  947. },
  948. };
  949. ```
  950. To set a custom name for namedExport, can use [`exportLocalsConvention`](#exportLocalsConvention) option as a function.
  951. Example below in the [`examples`](#examples) section.
  952. ##### `exportGlobals`
  953. Type:
  954. ```ts
  955. type exportsGLobals = boolean;
  956. ```
  957. Default: `false`
  958. Allow `css-loader` to export names from global class or id, so you can use that as local name.
  959. **webpack.config.js**
  960. ```js
  961. module.exports = {
  962. module: {
  963. rules: [
  964. {
  965. test: /\.css$/i,
  966. loader: "css-loader",
  967. options: {
  968. modules: {
  969. exportGlobals: true,
  970. },
  971. },
  972. },
  973. ],
  974. },
  975. };
  976. ```
  977. ##### `exportLocalsConvention`
  978. Type:
  979. ```ts
  980. type exportLocalsConvention =
  981. | "asIs"
  982. | "camelCase"
  983. | "camelCaseOnly"
  984. | "dashes"
  985. | "dashesOnly"
  986. | ((name: string) => string);
  987. ```
  988. Default: based on the `modules.namedExport` option value, if `true` - `camelCaseOnly`, otherwise `asIs`
  989. Style of exported class names.
  990. ###### `string`
  991. By default, the exported JSON keys mirror the class names (i.e `asIs` value).
  992. | Name | Type | Description |
  993. | :-------------------: | :------: | :----------------------------------------------------------------------------------------------- |
  994. | **`'asIs'`** | `string` | Class names will be exported as is. |
  995. | **`'camelCase'`** | `string` | Class names will be camelized, the original class name will not to be removed from the locals |
  996. | **`'camelCaseOnly'`** | `string` | Class names will be camelized, the original class name will be removed from the locals |
  997. | **`'dashes'`** | `string` | Only dashes in class names will be camelized |
  998. | **`'dashesOnly'`** | `string` | Dashes in class names will be camelized, the original class name will be removed from the locals |
  999. **file.css**
  1000. ```css
  1001. .class-name {
  1002. }
  1003. ```
  1004. **file.js**
  1005. ```js
  1006. import { className } from "file.css";
  1007. ```
  1008. **webpack.config.js**
  1009. ```js
  1010. module.exports = {
  1011. module: {
  1012. rules: [
  1013. {
  1014. test: /\.css$/i,
  1015. loader: "css-loader",
  1016. options: {
  1017. modules: {
  1018. exportLocalsConvention: "camelCase",
  1019. },
  1020. },
  1021. },
  1022. ],
  1023. },
  1024. };
  1025. ```
  1026. ###### `function`
  1027. **webpack.config.js**
  1028. ```js
  1029. module.exports = {
  1030. module: {
  1031. rules: [
  1032. {
  1033. test: /\.css$/i,
  1034. loader: "css-loader",
  1035. options: {
  1036. modules: {
  1037. exportLocalsConvention: function (name) {
  1038. return name.replace(/-/g, "_");
  1039. },
  1040. },
  1041. },
  1042. },
  1043. ],
  1044. },
  1045. };
  1046. ```
  1047. **webpack.config.js**
  1048. ```js
  1049. module.exports = {
  1050. module: {
  1051. rules: [
  1052. {
  1053. test: /\.css$/i,
  1054. loader: "css-loader",
  1055. options: {
  1056. modules: {
  1057. exportLocalsConvention: function (name) {
  1058. return [
  1059. name.replace(/-/g, "_"),
  1060. // dashesCamelCase
  1061. name.replace(/-+(\w)/g, (match, firstLetter) =>
  1062. firstLetter.toUpperCase()
  1063. ),
  1064. ];
  1065. },
  1066. },
  1067. },
  1068. },
  1069. ],
  1070. },
  1071. };
  1072. ```
  1073. ##### `exportOnlyLocals`
  1074. Type:
  1075. ```ts
  1076. type exportOnlyLocals = boolean;
  1077. ```
  1078. Default: `false`
  1079. Export only locals.
  1080. **Useful** when you use **css modules** for pre-rendering (for example SSR).
  1081. For pre-rendering with `mini-css-extract-plugin` you should use this option instead of `style-loader!css-loader` **in the pre-rendering bundle**.
  1082. It doesn't embed CSS but only exports the identifier mappings.
  1083. **webpack.config.js**
  1084. ```js
  1085. module.exports = {
  1086. module: {
  1087. rules: [
  1088. {
  1089. test: /\.css$/i,
  1090. loader: "css-loader",
  1091. options: {
  1092. modules: {
  1093. exportOnlyLocals: true,
  1094. },
  1095. },
  1096. },
  1097. ],
  1098. },
  1099. };
  1100. ```
  1101. ### `importLoaders`
  1102. Type:
  1103. ```ts
  1104. type importLoaders = number;
  1105. ```
  1106. Default: `0`
  1107. Allows to enables/disables or setups number of loaders applied before CSS loader for `@import` at-rules, CSS modules and ICSS imports, i.e. `@import`/`composes`/`@value value from './values.css'`/etc.
  1108. The option `importLoaders` allows you to configure how many loaders before `css-loader` should be applied to `@import`ed resources and CSS modules/ICSS imports.
  1109. **webpack.config.js**
  1110. ```js
  1111. module.exports = {
  1112. module: {
  1113. rules: [
  1114. {
  1115. test: /\.css$/i,
  1116. use: [
  1117. "style-loader",
  1118. {
  1119. loader: "css-loader",
  1120. options: {
  1121. importLoaders: 2,
  1122. // 0 => no loaders (default);
  1123. // 1 => postcss-loader;
  1124. // 2 => postcss-loader, sass-loader
  1125. },
  1126. },
  1127. "postcss-loader",
  1128. "sass-loader",
  1129. ],
  1130. },
  1131. ],
  1132. },
  1133. };
  1134. ```
  1135. This may change in the future when the module system (i. e. webpack) supports loader matching by origin.
  1136. ### `sourceMap`
  1137. Type:
  1138. ```ts
  1139. type sourceMap = boolean;
  1140. ```
  1141. Default: depends on the `compiler.devtool` value
  1142. By default generation of source maps depends on the [`devtool`](https://webpack.js.org/configuration/devtool/) option. All values enable source map generation except `eval` and `false` value.
  1143. **webpack.config.js**
  1144. ```js
  1145. module.exports = {
  1146. module: {
  1147. rules: [
  1148. {
  1149. test: /\.css$/i,
  1150. loader: "css-loader",
  1151. options: {
  1152. sourceMap: true,
  1153. },
  1154. },
  1155. ],
  1156. },
  1157. };
  1158. ```
  1159. ### `esModule`
  1160. Type:
  1161. ```ts
  1162. type esModule = boolean;
  1163. ```
  1164. Default: `true`
  1165. By default, `css-loader` generates JS modules that use the ES modules syntax.
  1166. 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/).
  1167. You can enable a CommonJS modules syntax using:
  1168. **webpack.config.js**
  1169. ```js
  1170. module.exports = {
  1171. module: {
  1172. rules: [
  1173. {
  1174. test: /\.css$/i,
  1175. loader: "css-loader",
  1176. options: {
  1177. esModule: false,
  1178. },
  1179. },
  1180. ],
  1181. },
  1182. };
  1183. ```
  1184. ### `exportType`
  1185. Type:
  1186. ```ts
  1187. type exportType = "array" | "string" | "css-style-sheet";
  1188. ```
  1189. Default: `'array'`
  1190. Allows exporting styles as array with modules, string or [constructable stylesheet](https://developers.google.com/web/updates/2019/02/constructable-stylesheets) (i.e. [`CSSStyleSheet`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet)).
  1191. Default value is `'array'`, i.e. loader exports array of modules with specific API which is used in `style-loader` or other.
  1192. **webpack.config.js**
  1193. ```js
  1194. module.exports = {
  1195. module: {
  1196. rules: [
  1197. {
  1198. assert: { type: "css" },
  1199. loader: "css-loader",
  1200. options: {
  1201. exportType: "css-style-sheet",
  1202. },
  1203. },
  1204. ],
  1205. },
  1206. };
  1207. ```
  1208. **src/index.js**
  1209. ```js
  1210. import sheet from "./styles.css" assert { type: "css" };
  1211. document.adoptedStyleSheets = [sheet];
  1212. shadowRoot.adoptedStyleSheets = [sheet];
  1213. ```
  1214. #### `'array'`
  1215. The default export is array of modules with specific API which is used in `style-loader` or other.
  1216. **webpack.config.js**
  1217. ```js
  1218. module.exports = {
  1219. module: {
  1220. rules: [
  1221. {
  1222. test: /\.(sa|sc|c)ss$/i,
  1223. use: ["style-loader", "css-loader", "postcss-loader", "sass-loader"],
  1224. },
  1225. ],
  1226. },
  1227. };
  1228. ```
  1229. **src/index.js**
  1230. ```js
  1231. // `style-loader` applies styles to DOM
  1232. import "./styles.css";
  1233. ```
  1234. #### `'string'`
  1235. > **Warning**
  1236. >
  1237. > You should not use [`style-loader`](https://github.com/webpack-contrib/style-loader) or [`mini-css-extract-plugin`](https://github.com/webpack-contrib/mini-css-extract-plugin) with this value.
  1238. > **Warning**
  1239. >
  1240. > The `esModule` option should be enabled if you want to use it with [`CSS modules`](https://github.com/webpack-contrib/css-loader#modules), by default for locals will be used [named export](https://github.com/webpack-contrib/css-loader#namedexport).
  1241. The default export is `string`.
  1242. **webpack.config.js**
  1243. ```js
  1244. module.exports = {
  1245. module: {
  1246. rules: [
  1247. {
  1248. test: /\.(sa|sc|c)ss$/i,
  1249. use: ["css-loader", "postcss-loader", "sass-loader"],
  1250. },
  1251. ],
  1252. },
  1253. };
  1254. ```
  1255. **src/index.js**
  1256. ```js
  1257. import sheet from "./styles.css";
  1258. console.log(sheet);
  1259. ```
  1260. #### `'css-style-sheet'`
  1261. > **Warning**
  1262. >
  1263. > `@import` rules not yet allowed, more [information](https://web.dev/css-module-scripts/#@import-rules-not-yet-allowed)
  1264. > **Warning**
  1265. >
  1266. > You don't need [`style-loader`](https://github.com/webpack-contrib/style-loader) anymore, please remove it.
  1267. > **Warning**
  1268. >
  1269. > The `esModule` option should be enabled if you want to use it with [`CSS modules`](https://github.com/webpack-contrib/css-loader#modules), by default for locals will be used [named export](https://github.com/webpack-contrib/css-loader#namedexport).
  1270. > **Warning**
  1271. >
  1272. > Source maps are not currently supported in `Chrome` due [bug](https://bugs.chromium.org/p/chromium/issues/detail?id=1174094&q=CSSStyleSheet%20source%20maps&can=2)
  1273. The default export is a [constructable stylesheet](https://developers.google.com/web/updates/2019/02/constructable-stylesheets) (i.e. [`CSSStyleSheet`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet)).
  1274. Useful for [custom elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) and shadow DOM.
  1275. More information:
  1276. - [Using CSS Module Scripts to import stylesheets](https://web.dev/css-module-scripts/)
  1277. - [Constructable Stylesheets: seamless reusable styles](https://developers.google.com/web/updates/2019/02/constructable-stylesheets)
  1278. **webpack.config.js**
  1279. ```js
  1280. module.exports = {
  1281. module: {
  1282. rules: [
  1283. {
  1284. assert: { type: "css" },
  1285. loader: "css-loader",
  1286. options: {
  1287. exportType: "css-style-sheet",
  1288. },
  1289. },
  1290. // For Sass/SCSS:
  1291. //
  1292. // {
  1293. // assert: { type: "css" },
  1294. // rules: [
  1295. // {
  1296. // loader: "css-loader",
  1297. // options: {
  1298. // exportType: "css-style-sheet",
  1299. // // Other options
  1300. // },
  1301. // },
  1302. // {
  1303. // loader: "sass-loader",
  1304. // options: {
  1305. // // Other options
  1306. // },
  1307. // },
  1308. // ],
  1309. // },
  1310. ],
  1311. },
  1312. };
  1313. ```
  1314. **src/index.js**
  1315. ```js
  1316. // Example for Sass/SCSS:
  1317. // import sheet from "./styles.scss" assert { type: "css" };
  1318. // Example for CSS modules:
  1319. // import sheet, { myClass } from "./styles.scss" assert { type: "css" };
  1320. // Example for CSS:
  1321. import sheet from "./styles.css" assert { type: "css" };
  1322. document.adoptedStyleSheets = [sheet];
  1323. shadowRoot.adoptedStyleSheets = [sheet];
  1324. ```
  1325. For migration purposes, you can use the following configuration:
  1326. ```js
  1327. module.exports = {
  1328. module: {
  1329. rules: [
  1330. {
  1331. test: /\.css$/i,
  1332. oneOf: [
  1333. {
  1334. assert: { type: "css" },
  1335. loader: "css-loader",
  1336. options: {
  1337. exportType: "css-style-sheet",
  1338. // Other options
  1339. },
  1340. },
  1341. {
  1342. use: [
  1343. "style-loader",
  1344. {
  1345. loader: "css-loader",
  1346. options: {
  1347. // Other options
  1348. },
  1349. },
  1350. ],
  1351. },
  1352. ],
  1353. },
  1354. ],
  1355. },
  1356. };
  1357. ```
  1358. ## Examples
  1359. ### Recommend
  1360. For `production` builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on.
  1361. This can be achieved by using the [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin), because it creates separate css files.
  1362. For `development` mode (including `webpack-dev-server`) you can use [style-loader](https://github.com/webpack-contrib/style-loader), because it injects CSS into the DOM using multiple `<style></style>` and works faster.
  1363. > **Note**
  1364. >
  1365. > Do not use `style-loader` and `mini-css-extract-plugin` together.
  1366. **webpack.config.js**
  1367. ```js
  1368. const MiniCssExtractPlugin = require("mini-css-extract-plugin");
  1369. const devMode = process.env.NODE_ENV !== "production";
  1370. module.exports = {
  1371. module: {
  1372. rules: [
  1373. {
  1374. // If you enable `experiments.css` or `experiments.futureDefaults`, please uncomment line below
  1375. // type: "javascript/auto",
  1376. test: /\.(sa|sc|c)ss$/i,
  1377. use: [
  1378. devMode ? "style-loader" : MiniCssExtractPlugin.loader,
  1379. "css-loader",
  1380. "postcss-loader",
  1381. "sass-loader",
  1382. ],
  1383. },
  1384. ],
  1385. },
  1386. plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]),
  1387. };
  1388. ```
  1389. ### Disable url resolving using the `/* webpackIgnore: true */` comment
  1390. With the help of the `/* webpackIgnore: true */`comment, it is possible to disable sources handling for rules and for individual declarations.
  1391. ```css
  1392. /* webpackIgnore: true */
  1393. @import url(./basic.css);
  1394. @import /* webpackIgnore: true */ url(./imported.css);
  1395. .class {
  1396. /* Disabled url handling for the all urls in the 'background' declaration */
  1397. color: red;
  1398. /* webpackIgnore: true */
  1399. background: url("./url/img.png"), url("./url/img.png");
  1400. }
  1401. .class {
  1402. /* Disabled url handling for the first url in the 'background' declaration */
  1403. color: red;
  1404. background:
  1405. /* webpackIgnore: true */ url("./url/img.png"), url("./url/img.png");
  1406. }
  1407. .class {
  1408. /* Disabled url handling for the second url in the 'background' declaration */
  1409. color: red;
  1410. background: url("./url/img.png"),
  1411. /* webpackIgnore: true */ url("./url/img.png");
  1412. }
  1413. /* prettier-ignore */
  1414. .class {
  1415. /* Disabled url handling for the second url in the 'background' declaration */
  1416. color: red;
  1417. background: url("./url/img.png"),
  1418. /* webpackIgnore: true */
  1419. url("./url/img.png");
  1420. }
  1421. /* prettier-ignore */
  1422. .class {
  1423. /* Disabled url handling for third and sixth urls in the 'background-image' declaration */
  1424. background-image: image-set(
  1425. url(./url/img.png) 2x,
  1426. url(./url/img.png) 3x,
  1427. /* webpackIgnore: true */ url(./url/img.png) 4x,
  1428. url(./url/img.png) 5x,
  1429. url(./url/img.png) 6x,
  1430. /* webpackIgnore: true */
  1431. url(./url/img.png) 7x
  1432. );
  1433. }
  1434. ```
  1435. ### Assets
  1436. The following `webpack.config.js` can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts as [Data URLs](https://tools.ietf.org/html/rfc2397) and copy larger files to the output directory.
  1437. **For webpack v5:**
  1438. **webpack.config.js**
  1439. ```js
  1440. module.exports = {
  1441. module: {
  1442. rules: [
  1443. {
  1444. test: /\.css$/i,
  1445. use: ["style-loader", "css-loader"],
  1446. },
  1447. {
  1448. test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
  1449. // More information here https://webpack.js.org/guides/asset-modules/
  1450. type: "asset",
  1451. },
  1452. ],
  1453. },
  1454. };
  1455. ```
  1456. ### Extract
  1457. For production builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on.
  1458. - This can be achieved by using the [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin) to extract the CSS when running in production mode.
  1459. - As an alternative, if seeking better development performance and css outputs that mimic production. [extract-css-chunks-webpack-plugin](https://github.com/faceyspacey/extract-css-chunks-webpack-plugin) offers a hot module reload friendly, extended version of mini-css-extract-plugin. HMR real CSS files in dev, works like mini-css in non-dev
  1460. ### Pure CSS, CSS modules and PostCSS
  1461. When you have pure CSS (without CSS modules), CSS modules and PostCSS in your project you can use this setup:
  1462. **webpack.config.js**
  1463. ```js
  1464. module.exports = {
  1465. module: {
  1466. rules: [
  1467. {
  1468. // For pure CSS - /\.css$/i,
  1469. // For Sass/SCSS - /\.((c|sa|sc)ss)$/i,
  1470. // For Less - /\.((c|le)ss)$/i,
  1471. test: /\.((c|sa|sc)ss)$/i,
  1472. use: [
  1473. "style-loader",
  1474. {
  1475. loader: "css-loader",
  1476. options: {
  1477. // Run `postcss-loader` on each CSS `@import` and CSS modules/ICSS imports, do not forget that `sass-loader` compile non CSS `@import`'s into a single file
  1478. // If you need run `sass-loader` and `postcss-loader` on each CSS `@import` please set it to `2`
  1479. importLoaders: 1,
  1480. },
  1481. },
  1482. {
  1483. loader: "postcss-loader",
  1484. options: { plugins: () => [postcssPresetEnv({ stage: 0 })] },
  1485. },
  1486. // Can be `less-loader`
  1487. {
  1488. loader: "sass-loader",
  1489. },
  1490. ],
  1491. },
  1492. // For webpack v5
  1493. {
  1494. test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
  1495. // More information here https://webpack.js.org/guides/asset-modules/
  1496. type: "asset",
  1497. },
  1498. ],
  1499. },
  1500. };
  1501. ```
  1502. ### Resolve unresolved URLs using an alias
  1503. **index.css**
  1504. ```css
  1505. .class {
  1506. background: url(/assets/unresolved/img.png);
  1507. }
  1508. ```
  1509. **webpack.config.js**
  1510. ```js
  1511. module.exports = {
  1512. module: {
  1513. rules: [
  1514. {
  1515. test: /\.css$/i,
  1516. use: ["style-loader", "css-loader"],
  1517. },
  1518. ],
  1519. },
  1520. resolve: {
  1521. alias: {
  1522. "/assets/unresolved/img.png": path.resolve(
  1523. __dirname,
  1524. "assets/real-path-to-img/img.png"
  1525. ),
  1526. },
  1527. },
  1528. };
  1529. ```
  1530. ### Named export with custom export names
  1531. **webpack.config.js**
  1532. ```js
  1533. module.exports = {
  1534. module: {
  1535. rules: [
  1536. {
  1537. test: /\.css$/i,
  1538. loader: "css-loader",
  1539. options: {
  1540. modules: {
  1541. namedExport: true,
  1542. exportLocalsConvention: function (name) {
  1543. return name.replace(/-/g, "_");
  1544. },
  1545. },
  1546. },
  1547. },
  1548. ],
  1549. },
  1550. };
  1551. ```
  1552. ### Separating `Interoperable CSS`-only and `CSS Module` features
  1553. The following setup is an example of allowing `Interoperable CSS` features only (such as `:import` and `:export`) without using further `CSS Module` functionality by setting `mode` option for all files that do not match `*.module.scss` naming convention. This is for reference as having `ICSS` features applied to all files was default `css-loader` behavior before v4.
  1554. Meanwhile all files matching `*.module.scss` are treated as `CSS Modules` in this example.
  1555. An example case is assumed where a project requires canvas drawing variables to be synchronized with CSS - canvas drawing uses the same color (set by color name in JavaScript) as HTML background (set by class name in CSS).
  1556. **webpack.config.js**
  1557. ```js
  1558. module.exports = {
  1559. module: {
  1560. rules: [
  1561. // ...
  1562. // --------
  1563. // SCSS ALL EXCEPT MODULES
  1564. {
  1565. test: /\.scss$/i,
  1566. exclude: /\.module\.scss$/i,
  1567. use: [
  1568. {
  1569. loader: "style-loader",
  1570. },
  1571. {
  1572. loader: "css-loader",
  1573. options: {
  1574. importLoaders: 1,
  1575. modules: {
  1576. mode: "icss",
  1577. },
  1578. },
  1579. },
  1580. {
  1581. loader: "sass-loader",
  1582. },
  1583. ],
  1584. },
  1585. // --------
  1586. // SCSS MODULES
  1587. {
  1588. test: /\.module\.scss$/i,
  1589. use: [
  1590. {
  1591. loader: "style-loader",
  1592. },
  1593. {
  1594. loader: "css-loader",
  1595. options: {
  1596. importLoaders: 1,
  1597. modules: {
  1598. mode: "local",
  1599. },
  1600. },
  1601. },
  1602. {
  1603. loader: "sass-loader",
  1604. },
  1605. ],
  1606. },
  1607. // --------
  1608. // ...
  1609. ],
  1610. },
  1611. };
  1612. ```
  1613. **variables.scss**
  1614. File treated as `ICSS`-only.
  1615. ```scss
  1616. $colorBackground: red;
  1617. :export {
  1618. colorBackgroundCanvas: $colorBackground;
  1619. }
  1620. ```
  1621. **Component.module.scss**
  1622. File treated as `CSS Module`.
  1623. ```scss
  1624. @import "variables.scss";
  1625. .componentClass {
  1626. background-color: $colorBackground;
  1627. }
  1628. ```
  1629. **Component.jsx**
  1630. Using both `CSS Module` functionality as well as SCSS variables directly in JavaScript.
  1631. ```jsx
  1632. import svars from "variables.scss";
  1633. import styles from "Component.module.scss";
  1634. // Render DOM with CSS modules class name
  1635. // <div className={styles.componentClass}>
  1636. // <canvas ref={mountsCanvas}/>
  1637. // </div>
  1638. // Somewhere in JavaScript canvas drawing code use the variable directly
  1639. // const ctx = mountsCanvas.current.getContext('2d',{alpha: false});
  1640. ctx.fillStyle = `${svars.colorBackgroundCanvas}`;
  1641. ```
  1642. ## Contributing
  1643. Please take a moment to read our contributing guidelines if you haven't yet done so.
  1644. [CONTRIBUTING](./.github/CONTRIBUTING.md)
  1645. ## License
  1646. [MIT](./LICENSE)
  1647. [npm]: https://img.shields.io/npm/v/css-loader.svg
  1648. [npm-url]: https://npmjs.com/package/css-loader
  1649. [node]: https://img.shields.io/node/v/css-loader.svg
  1650. [node-url]: https://nodejs.org
  1651. [tests]: https://github.com/webpack-contrib/css-loader/workflows/css-loader/badge.svg
  1652. [tests-url]: https://github.com/webpack-contrib/css-loader/actions
  1653. [cover]: https://codecov.io/gh/webpack-contrib/css-loader/branch/master/graph/badge.svg
  1654. [cover-url]: https://codecov.io/gh/webpack-contrib/css-loader
  1655. [discussion]: https://img.shields.io/github/discussions/webpack/webpack
  1656. [discussion-url]: https://github.com/webpack/webpack/discussions
  1657. [size]: https://packagephobia.now.sh/badge?p=css-loader
  1658. [size-url]: https://packagephobia.now.sh/result?p=css-loader