UNPKG

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