Gathering detailed insights and metrics for css-loader-1
Gathering detailed insights and metrics for css-loader-1
Gathering detailed insights and metrics for css-loader-1
Gathering detailed insights and metrics for css-loader-1
npm install css-loader-1
Module System
Unable to determine the module system for this package.
Min. Node Version
Typescript Support
Node Version
NPM Version
4,312 Stars
856 Commits
604 Forks
59 Watching
4 Branches
135 Contributors
Updated on 28 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-16.3%
159
Compared to previous day
Last week
1.4%
1,052
Compared to previous week
Last month
11.8%
4,451
Compared to previous month
Last year
-24.1%
62,197
Compared to previous year
12
1
The css-loader
interprets @import
and url()
like import/require()
and will resolve them.
[!WARNING]
To use the latest version of css-loader, webpack@5 is required
To begin, you'll need to install css-loader
:
1npm install --save-dev css-loader
or
1yarn add -D css-loader
or
1pnpm add -D css-loader
Then add the plugin to your webpack
config. For example:
file.js
1import * as css from "file.css";
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 use: ["style-loader", "css-loader"], 7 }, 8 ], 9 }, 10};
And run webpack
via your preferred method.
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.
url
Type:
1type url = 2 | boolean 3 | { 4 filter: (url: string, resourcePath: string) => boolean; 5 };
Default: true
Allow to enable/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, absolute paths are parsed based on the server root.
Examples resolutions:
1url(image.png) => require('./image.png') 2url('image.png') => require('./image.png') 3url(./image.png) => require('./image.png') 4url('./image.png') => require('./image.png') 5url('http://dontwritehorriblecode.com/2112.png') => require('http://dontwritehorriblecode.com/2112.png') 6image-set(url('image2x.png') 1x, url('image1x.png') 2x) => require('./image1x.png') and require('./image2x.png')
To import assets from a node_modules
path (include resolve.modules
) and for alias
, prefix it with a ~
:
1url(~module/image.png) => require('module/image.png') 2url('~module/image.png') => require('module/image.png') 3url(~aliasDirectory/image.png) => require('otherDirectory/image.png')
boolean
Enable/disable url()
resolving.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 url: true, 9 }, 10 }, 11 ], 12 }, 13};
object
Allow to filter url()
. All filtered url()
will not be resolved (left in the code as they were written).
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 url: { 9 filter: (url, resourcePath) => { 10 // resourcePath - path to css file 11 12 // Don't handle `img.png` urls 13 if (url.includes("img.png")) { 14 return false; 15 } 16 17 // Don't handle images under root-relative /external_images/ 18 if (/^\/external_images\//.test(path)) { 19 return false; 20 } 21 22 return true; 23 }, 24 }, 25 }, 26 }, 27 ], 28 }, 29};
import
Type:
1type importFn = 2 | boolean 3 | { 4 filter: ( 5 url: string, 6 media: string, 7 resourcePath: string, 8 supports?: string, 9 layer?: string, 10 ) => boolean; 11 };
Default: true
Allows to enables/disables @import
at-rules handling.
Control @import
resolving. Absolute urls in @import
will be moved in runtime code.
Examples resolutions:
@import 'style.css' => require('./style.css')
@import url(style.css) => require('./style.css')
@import url('style.css') => require('./style.css')
@import './style.css' => require('./style.css')
@import url(./style.css) => require('./style.css')
@import url('./style.css') => require('./style.css')
@import url('http://dontwritehorriblecode.com/style.css') => @import url('http://dontwritehorriblecode.com/style.css') in runtime
To import styles from a node_modules
path (include resolve.modules
) and for alias
, prefix it with a ~
:
@import url(~module/style.css) => require('module/style.css')
@import url('~module/style.css') => require('module/style.css')
@import url(~aliasDirectory/style.css) => require('otherDirectory/style.css')
boolean
Enable/disable @import
resolving.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 import: true, 9 }, 10 }, 11 ], 12 }, 13};
object
filter
Type:
1type filter = (url: string, media: string, resourcePath: string) => boolean;
Default: undefined
Allow to filter @import
. All filtered @import
will not be resolved (left in the code as they were written).
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 import: { 9 filter: (url, media, resourcePath) => { 10 // resourcePath - path to css file 11 12 // Don't handle `style.css` import 13 if (url.includes("style.css")) { 14 return false; 15 } 16 17 return true; 18 }, 19 }, 20 }, 21 }, 22 ], 23 }, 24};
modules
Type:
1type modules = 2 | boolean 3 | "local" 4 | "global" 5 | "pure" 6 | "icss" 7 | { 8 auto: boolean | regExp | ((resourcePath: string) => boolean); 9 mode: 10 | "local" 11 | "global" 12 | "pure" 13 | "icss" 14 | ((resourcePath) => "local" | "global" | "pure" | "icss"); 15 localIdentName: string; 16 localIdentContext: string; 17 localIdentHashSalt: string; 18 localIdentHashFunction: string; 19 localIdentHashDigest: string; 20 localIdentRegExp: string | regExp; 21 getLocalIdent: ( 22 context: LoaderContext, 23 localIdentName: string, 24 localName: string, 25 ) => string; 26 namedExport: boolean; 27 exportGlobals: boolean; 28 exportLocalsConvention: 29 | "as-is" 30 | "camel-case" 31 | "camel-case-only" 32 | "dashes" 33 | "dashes-only" 34 | ((name: string) => string); 35 exportOnlyLocals: boolean; 36 getJSON: ({ 37 resourcePath, 38 imports, 39 exports, 40 replacements, 41 }: { 42 resourcePath: string; 43 imports: object[]; 44 exports: object[]; 45 replacements: object[]; 46 }) => Promise<void> | void; 47 };
Default: undefined
Allows to enable/disable CSS Modules or ICSS and setup configuration:
undefined
- enable CSS modules for all files matching /\.module\.\w+$/i.test(filename)
and /\.icss\.\w+$/i.test(filename)
regexp.true
- enable CSS modules for all files.false
- disables CSS Modules for all files.string
- disables CSS Modules for all files and set the mode
option, more information you can read hereobject
- 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 hereThe modules
option enables/disables the CSS Modules specification and setup basic behaviour.
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.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: true, 9 }, 10 }, 11 ], 12 }, 13};
Features
Scope
Using local
value requires you to specify :global
classes.
Using global
value requires you to specify :local
classes.
Using pure
value requires selectors must contain at least one local class or id.
You can find more information here.
Styles can be locally scoped to avoid globally scoping styles.
The syntax :local(.className)
can be used to declare className
in the local scope. The local identifiers are exported by the module.
With :local
(without brackets) local mode can be switched on for this selector.
The :global(.className)
notation can be used to declare an explicit global selector.
With :global
(without brackets) global mode can be switched on for this selector.
The loader replaces local selectors with unique identifiers. The chosen unique identifiers are exported by the module.
1:local(.className) { 2 background: red; 3} 4:local .className { 5 color: green; 6} 7:local(.className .subClass) { 8 color: green; 9} 10:local .className .subClass :global(.global-class-name) { 11 color: blue; 12}
1._23_aKvs-b8bW2Vg3fwHozO { 2 background: red; 3} 4._23_aKvs-b8bW2Vg3fwHozO { 5 color: green; 6} 7._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 { 8 color: green; 9} 10._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name { 11 color: blue; 12}
[!NOTE]
Identifiers are exported
1exports.locals = { 2 className: "_23_aKvs-b8bW2Vg3fwHozO", 3 subClass: "_13LGdX8RMStbBE9w-t0gZ1", 4};
CamelCase is recommended for local selectors. They are easier to use within the imported JS module.
You can use :local(#someId)
, but this is not recommended. Use classes instead of ids.
Composing
When declaring a local classname you can compose a local class from another local classname.
1:local(.className) { 2 background: red; 3 color: yellow; 4} 5 6:local(.subClass) { 7 composes: className; 8 background: blue; 9}
This doesn't result in any change to the CSS itself but exports multiple classnames.
1exports.locals = { 2 className: "_23_aKvs-b8bW2Vg3fwHozO", 3 subClass: "_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO", 4};
1._23_aKvs-b8bW2Vg3fwHozO { 2 background: red; 3 color: yellow; 4} 5 6._13LGdX8RMStbBE9w-t0gZ1 { 7 background: blue; 8}
Importing
To import a local classname from another module.
[!NOTE]
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.
1:local(.continueButton) { 2 composes: button from "library/button.css"; 3 background: red; 4}
1:local(.nameEdit) { 2 composes: edit highlight from "./edit.css"; 3 background: red; 4}
To import from multiple modules use multiple composes:
rules.
1:local(.className) { 2 composes: 3 edit highlight from "./edit.css", 4 button from "module/button.css", 5 classFromThisModule; 6 background: red; 7}
or
1:local(.className) { 2 composes: edit highlight from "./edit.css"; 3 composes: button from "module/button.css"; 4 composes: classFromThisModule; 5 background: red; 6}
Values
You can use @value
to specific values to be reused throughout a document.
We recommend use prefix v-
for values, s-
for selectors and m-
for media at-rules.
1@value v-primary: #BF4040; 2@value s-black: black-selector; 3@value m-large: (min-width: 960px); 4 5.header { 6 color: v-primary; 7 padding: 0 10px; 8} 9 10.s-black { 11 color: black; 12} 13 14@media m-large { 15 .header { 16 padding: 0 20px; 17 } 18}
boolean
Enable CSS Modules features.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: true, 9 }, 10 }, 11 ], 12 }, 13};
string
Enable CSS Modules features and setup mode
.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 // Using `local` value has same effect like using `modules: true` 9 modules: "global", 10 }, 11 }, 12 ], 13 }, 14};
object
Enable CSS Modules features and setup options for them.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 mode: "local", 10 auto: true, 11 exportGlobals: true, 12 localIdentName: "[path][name]__[local]--[hash:base64:5]", 13 localIdentContext: path.resolve(__dirname, "src"), 14 localIdentHashSalt: "my-custom-hash", 15 namedExport: true, 16 exportLocalsConvention: "as-is", 17 exportOnlyLocals: false, 18 getJSON: ({ resourcePath, imports, exports, replacements }) => {}, 19 }, 20 }, 21 }, 22 ], 23 }, 24};
auto
Type:
1type auto = 2 | boolean 3 | regExp 4 | (( 5 resourcePath: string, 6 resourceQuery: string, 7 resourceFragment: string, 8 ) => boolean);
Default: undefined
Allows auto enable CSS modules/ICSS based on the filename, query or fragment when modules
option is object.
Possible values:
undefined
- enable CSS modules for all files.true
- enable CSS modules for all files matching /\.module\.\w+$/i.test(filename)
and /\.icss\.\w+$/i.test(filename)
regexp.false
- disables CSS Modules.RegExp
- enable CSS modules for all files matching /RegExp/i.test(filename)
regexp.function
- enable CSS Modules for files based on the filename satisfying your filter function check.boolean
Possible values:
true
- enables CSS modules or interoperable CSS format, sets the modules.mode
option to local
value for all files which satisfy /\.module(s)?\.\w+$/i.test(filename)
condition or sets the modules.mode
option to icss
value for all files which satisfy /\.icss\.\w+$/i.test(filename)
conditionfalse
- disables CSS modules or interoperable CSS format based on filenamewebpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 auto: true, 10 }, 11 }, 12 }, 13 ], 14 }, 15};
RegExp
Enable CSS modules for files based on the filename satisfying your regex check.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 auto: /\.custom-module\.\w+$/i, 10 }, 11 }, 12 }, 13 ], 14 }, 15};
function
Enable CSS modules for files based on the filename, query or fragment satisfying your filter function check.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 auto: (resourcePath, resourceQuery, resourceFragment) => { 10 return resourcePath.endsWith(".custom-module.css"); 11 }, 12 }, 13 }, 14 }, 15 ], 16 }, 17};
mode
Type:
1type mode = 2 | "local" 3 | "global" 4 | "pure" 5 | "icss" 6 | (( 7 resourcePath: string, 8 resourceQuery: string, 9 resourceFragment: string, 10 ) => "local" | "global" | "pure" | "icss");
Default: 'local'
Setup mode
option. You can omit the value when you want local
mode.
Controls the level of compilation applied to the input styles.
The local
, global
, and pure
handles class
and id
scoping and @value
values.
The icss
will only compile the low level Interoperable CSS
format for declaring :import
and :export
dependencies between CSS and other languages.
ICSS underpins CSS Module support, and provides a low level syntax for other tools to implement CSS-module variations of their own.
string
Possible values - local
, global
, pure
, and icss
.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 mode: "global", 10 }, 11 }, 12 }, 13 ], 14 }, 15};
function
Allows set different values for the mode
option based on the filename, query or fragment.
Possible return values - local
, global
, pure
and icss
.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 // Callback must return "local", "global", or "pure" values 10 mode: (resourcePath, resourceQuery, resourceFragment) => { 11 if (/pure.css$/i.test(resourcePath)) { 12 return "pure"; 13 } 14 15 if (/global.css$/i.test(resourcePath)) { 16 return "global"; 17 } 18 19 return "local"; 20 }, 21 }, 22 }, 23 }, 24 ], 25 }, 26};
localIdentName
Type:
1type localIdentName = string;
Default: '[hash:base64]'
Allows to configure the generated local ident name.
For more information on options see:
Supported template strings:
[name]
the basename of the resource[folder]
the folder the resource relative to the compiler.context
option or modules.localIdentContext
option.[path]
the path of the resource relative to the compiler.context
option or modules.localIdentContext
option.[file]
- filename and path.[ext]
- extension with leading .
.[hash]
- the hash of the string, generated based on localIdentHashSalt
, localIdentHashFunction
, localIdentHashDigest
, localIdentHashDigestLength
, localIdentContext
, resourcePath
and exportName
[<hashFunction>:hash:<hashDigest>:<hashDigestLength>]
- hash with hash settings.[local]
- original class.Recommendations:
'[path][name]__[local]'
for development'[hash:base64]'
for productionThe [local]
placeholder contains original class.
Note: all reserved (<>:"/\|?*
) and control filesystem characters (excluding characters in the [local]
placeholder) will be converted to -
.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 localIdentName: "[path][name]__[local]--[hash:base64:5]", 10 }, 11 }, 12 }, 13 ], 14 }, 15};
localIdentContext
Type:
1type localIdentContex = string;
Default: compiler.context
Allows to redefine basic loader context for local ident name.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 localIdentContext: path.resolve(__dirname, "src"), 10 }, 11 }, 12 }, 13 ], 14 }, 15};
localIdentHashSalt
Type:
1type localIdentHashSalt = string;
Default: undefined
Allows to add custom hash to generate more unique classes. For more information see output.hashSalt.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 localIdentHashSalt: "hash", 10 }, 11 }, 12 }, 13 ], 14 }, 15};
localIdentHashFunction
Type:
1type localIdentHashFunction = string;
Default: md4
Allows to specify hash function to generate classes . For more information see output.hashFunction.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 localIdentHashFunction: "md4", 10 }, 11 }, 12 }, 13 ], 14 }, 15};
localIdentHashDigest
Type:
1type localIdentHashDigest = string;
Default: hex
Allows to specify hash digest to generate classes. For more information see output.hashDigest.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 localIdentHashDigest: "base64", 10 }, 11 }, 12 }, 13 ], 14 }, 15};
localIdentHashDigestLength
Type:
1type localIdentHashDigestLength = number;
Default: 20
Allows to specify hash digest length to generate classes. For more information see output.hashDigestLength.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 localIdentHashDigestLength: 5, 10 }, 11 }, 12 }, 13 ], 14 }, 15};
hashStrategy
Type: 'resource-path-and-local-name' | 'minimal-subset'
Default: 'resource-path-and-local-name'
Should local name be used when computing the hash.
'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.'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.webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 hashStrategy: "minimal-subset", 10 }, 11 }, 12 }, 13 ], 14 }, 15};
localIdentRegExp
Type:
1type localIdentRegExp = string | RegExp;
Default: undefined
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 localIdentRegExp: /page-(.*)\.css/i, 10 }, 11 }, 12 }, 13 ], 14 }, 15};
getLocalIdent
Type:
1type getLocalIdent = ( 2 context: LoaderContext, 3 localIdentName: string, 4 localName: string, 5) => string;
Default: undefined
Allows to specify a function to generate the classname.
By default we use built-in function to generate a classname.
If the custom function returns null
or undefined
, we fallback to the
built-in function to generate the classname.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 getLocalIdent: (context, localIdentName, localName, options) => { 10 return "whatever_random_class_name"; 11 }, 12 }, 13 }, 14 }, 15 ], 16 }, 17};
namedExport
Type:
1type namedExport = boolean;
Default: Depends on the value of the esModule
option. If the value of the esModule
options is true
, this value will also be true
, otherwise it will be false
.
Enables/disables ES modules named export for locals.
[!WARNING]
Because it is not allowed to use the
default
class in CSS when thenamedExport
istrue
(since ECMA modules have a reserved keyworddefault
for default export), it will be automatically renamed to the_default
class.
styles.css
1.foo-baz { 2 color: red; 3} 4.bar { 5 color: blue; 6} 7.default { 8 color: green; 9}
index.js
1import * as styles from "./styles.css"; 2 3// If using `exportLocalsConvention: "as-is"` (default value): 4console.log(styles["foo-baz"], styles.bar); 5 6// If using `exportLocalsConvention: "camel-case-only"`: 7console.log(styles.fooBaz, styles.bar); 8 9// For the `default` classname 10console.log(styles["_default"]);
You can enable a ES module named export using:
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 esModule: true, 9 modules: { 10 namedExport: true, 11 }, 12 }, 13 }, 14 ], 15 }, 16};
To set a custom name for namedExport, can use exportLocalsConvention
option as a function.
Example below in the examples
section.
exportGlobals
Type:
1type exportsGLobals = boolean;
Default: false
Allow css-loader
to export names from global class or id, so you can use that as local name.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 exportGlobals: true, 10 }, 11 }, 12 }, 13 ], 14 }, 15};
exportLocalsConvention
Type:
1type exportLocalsConvention = 2 | "as-is" 3 | "camel-case" 4 | "camel-case-only" 5 | "dashes" 6 | "dashes-only" 7 | ((name: string) => string);
Default: Depends on the value of the modules.namedExport
option, if true
- as-is
, otherwise camel-case-only
.
[!WARNING]
Names of locals are converted to camelcase when the named export is
false
, i.e. theexportLocalsConvention
option hascamelCaseOnly
value by default. You can set this back to any other valid option but selectors which are not valid JavaScript identifiers may run into problems which do not implement the entire modules specification.
Style of exported class names.
string
By default, the exported JSON keys mirror the class names (i.e as-is
value).
Name | Type | Description |
---|---|---|
'as-is' | string | Class names will be exported as is. |
'camel-case' | string | Class names will be camelized, the original class name will not to be removed from the locals |
'camel-case-only' | string | Class names will be camelized, the original class name will be removed from the locals |
'dashes' | string | Only dashes in class names will be camelized |
'dashes-only' | string | Dashes in class names will be camelized, the original class name will be removed from the locals |
file.css
1.class-name { 2}
file.js
1import { className } from "file.css";
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 exportLocalsConvention: "camel-case-only", 10 }, 11 }, 12 }, 13 ], 14 }, 15};
function
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 exportLocalsConvention: function (name) { 10 return name.replace(/-/g, "_"); 11 }, 12 }, 13 }, 14 }, 15 ], 16 }, 17};
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 exportLocalsConvention: function (name) { 10 return [ 11 name.replace(/-/g, "_"), 12 // dashesCamelCase 13 name.replace(/-+(\w)/g, (match, firstLetter) => 14 firstLetter.toUpperCase(), 15 ), 16 ]; 17 }, 18 }, 19 }, 20 }, 21 ], 22 }, 23};
exportOnlyLocals
Type:
1type exportOnlyLocals = boolean;
Default: false
Export only locals.
Useful when you use css modules for pre-rendering (for example SSR).
For pre-rendering with mini-css-extract-plugin
you should use this option instead of style-loader!css-loader
in the pre-rendering bundle.
It doesn't embed CSS but only exports the identifier mappings.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 exportOnlyLocals: true, 10 }, 11 }, 12 }, 13 ], 14 }, 15};
getJSON
Type:
1type getJSON = ({ 2 resourcePath, 3 imports, 4 exports, 5 replacements, 6}: { 7 resourcePath: string; 8 imports: object[]; 9 exports: object[]; 10 replacements: object[]; 11}) => Promise<void> | void;
Default: undefined
Enables a callback to output the CSS modules mapping JSON. The callback is invoked with an object containing the following:
resourcePath
: the absolute path of the original resource, e.g., /foo/bar/baz.module.css
imports
: an array of import objects with data about import types and file paths, e.g.,
1[ 2 { 3 "type": "icss_import", 4 "importName": "___CSS_LOADER_ICSS_IMPORT_0___", 5 "url": "\"-!../../../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../../../../node_modules/postcss-loader/dist/cjs.js!../../../../../node_modules/sass-loader/dist/cjs.js!../../../../baz.module.css\"", 6 "icss": true, 7 "index": 0 8 } 9]
(Note that this will include all imports, not just those relevant to CSS modules.)
exports
: an array of export objects with exported names and values, e.g.,1[ 2 { 3 "name": "main", 4 "value": "D2Oy" 5 } 6]
replacements
: an array of import replacement objects used for linking imports
and exports
, e.g.,1{ 2 "replacementName": "___CSS_LOADER_ICSS_IMPORT_0_REPLACEMENT_0___", 3 "importName": "___CSS_LOADER_ICSS_IMPORT_0___", 4 "localName": "main" 5}
Using getJSON
, it's possible to output a files with all CSS module mappings.
In the following example, we use getJSON
to cache canonical mappings and
add stand-ins for any composed values (through composes
), and we use a custom plugin
to consolidate the values and output them to a file:
webpack.config.js
1const path = require("path"); 2const fs = require("fs"); 3 4const CSS_LOADER_REPLACEMENT_REGEX = 5 /(___CSS_LOADER_ICSS_IMPORT_\d+_REPLACEMENT_\d+___)/g; 6const REPLACEMENT_REGEX = /___REPLACEMENT\[(.*?)]\[(.*?)]___/g; 7const IDENTIFIER_REGEX = /\[(.*?)]\[(.*?)]/; 8const replacementsMap = {}; 9const canonicalValuesMap = {}; 10const allExportsJson = {}; 11 12function generateIdentifier(resourcePath, localName) { 13 return `[${resourcePath}][${localName}]`; 14} 15 16function addReplacements(resourcePath, imports, exportsJson, replacements) { 17 const importReplacementsMap = {}; 18 19 // create a dict to quickly identify imports and get their absolute stand-in strings in the currently loaded file 20 // e.g., { '___CSS_LOADER_ICSS_IMPORT_0_REPLACEMENT_0___': '___REPLACEMENT[/foo/bar/baz.css][main]___' } 21 importReplacementsMap[resourcePath] = replacements.reduce( 22 (acc, { replacementName, importName, localName }) => { 23 const replacementImportUrl = imports.find( 24 (importData) => importData.importName === importName, 25 ).url; 26 const relativePathRe = /.*!(.*)"/; 27 const [, relativePath] = replacementImportUrl.match(relativePathRe); 28 const importPath = path.resolve(path.dirname(resourcePath), relativePath); 29 const identifier = generateIdentifier(importPath, localName); 30 return { ...acc, [replacementName]: `___REPLACEMENT${identifier}___` }; 31 }, 32 {}, 33 ); 34 35 // iterate through the raw exports and add stand-in variables 36 // ('___REPLACEMENT[<absolute_path>][<class_name>]___') 37 // to be replaced in the plugin below 38 for (const [localName, classNames] of Object.entries(exportsJson)) { 39 const identifier = generateIdentifier(resourcePath, localName); 40 41 if (CSS_LOADER_REPLACEMENT_REGEX.test(classNames)) { 42 // if there are any replacements needed in the concatenated class names, 43 // add them all to the replacements map to be replaced altogether later 44 replacementsMap[identifier] = classNames.replaceAll( 45 CSS_LOADER_REPLACEMENT_REGEX, 46 (_, replacementName) => 47 importReplacementsMap[resourcePath][replacementName], 48 ); 49 } else { 50 // otherwise, no class names need replacements so we can add them to 51 // canonical values map and all exports JSON verbatim 52 canonicalValuesMap[identifier] = classNames; 53 54 allExportsJson[resourcePath] = allExportsJson[resourcePath] || {}; 55 allExportsJson[resourcePath][localName] = classNames; 56 } 57 } 58} 59 60function replaceReplacements(classNames) { 61 return classNames.replaceAll( 62 REPLACEMENT_REGEX, 63 (_, resourcePath, localName) => { 64 const identifier = generateIdentifier(resourcePath, localName); 65 66 if (identifier in canonicalValuesMap) { 67 return canonicalValuesMap[identifier]; 68 } 69 70 // Recurse through other stand-in that may be imports 71 const canonicalValue = replaceReplacements(replacementsMap[identifier]); 72 73 canonicalValuesMap[identifier] = canonicalValue; 74 75 return canonicalValue; 76 }, 77 ); 78} 79 80function getJSON({ resourcePath, imports, exports, replacements }) { 81 const exportsJson = exports.reduce((acc, { name, value }) => { 82 return { ...acc, [name]: value }; 83 }, {}); 84 85 if (replacements.length > 0) { 86 // replacements present --> add stand-in values for absolute paths and local names, 87 // which will be resolved to their canonical values in the plugin below 88 addReplacements(resourcePath, imports, exportsJson, replacements); 89 } else { 90 // no replacements present --> add to canonicalValuesMap verbatim 91 // since all values here are canonical/don't need resolution 92 for (const [key, value] of Object.entries(exportsJson)) { 93 const id = `[${resourcePath}][${key}]`; 94 95 canonicalValuesMap[id] = value; 96 } 97 98 allExportsJson[resourcePath] = exportsJson; 99 } 100} 101 102class CssModulesJsonPlugin { 103 constructor(options) { 104 this.options = options; 105 } 106 107 // eslint-disable-next-line class-methods-use-this 108 apply(compiler) { 109 compiler.hooks.emit.tap("CssModulesJsonPlugin", () => { 110 for (const [identifier, classNames] of Object.entries(replacementsMap)) { 111 const adjustedClassNames = replaceReplacements(classNames); 112 113 replacementsMap[identifier] = adjustedClassNames; 114 115 const [, resourcePath, localName] = identifier.match(IDENTIFIER_REGEX); 116 117 allExportsJson[resourcePath] = allExportsJson[resourcePath] || {}; 118 allExportsJson[resourcePath][localName] = adjustedClassNames; 119 } 120 121 fs.writeFileSync( 122 this.options.filepath, 123 JSON.stringify( 124 // Make path to be relative to `context` (your project root) 125 Object.fromEntries( 126 Object.entries(allExportsJson).map((key) => { 127 key[0] = path 128 .relative(compiler.context, key[0]) 129 .replace(/\\/g, "/"); 130 131 return key; 132 }), 133 ), 134 null, 135 2, 136 ), 137 "utf8", 138 ); 139 }); 140 } 141} 142 143module.exports = { 144 module: { 145 rules: [ 146 { 147 test: /\.css$/i, 148 loader: "css-loader", 149 options: { modules: { getJSON } }, 150 }, 151 ], 152 }, 153 plugins: [ 154 new CssModulesJsonPlugin({ 155 filepath: path.resolve(__dirname, "./output.css.json"), 156 }), 157 ], 158};
In the above, all import aliases are replaced with ___REPLACEMENT[<resourcePath>][<localName>]___
in getJSON
, and they're resolved in the custom plugin. All CSS mappings are contained in allExportsJson
:
1{ 2 "foo/bar/baz.module.css": { 3 "main": "D2Oy", 4 "header": "thNN" 5 }, 6 "foot/bear/bath.module.css": { 7 "logo": "sqiR", 8 "info": "XMyI" 9 } 10}
This is saved to a local file named output.css.json
.
importLoaders
Type:
1type importLoaders = number;
Default: 0
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.
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.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 use: [ 7 "style-loader", 8 { 9 loader: "css-loader", 10 options: { 11 importLoaders: 2, 12 // 0 => no loaders (default); 13 // 1 => postcss-loader; 14 // 2 => postcss-loader, sass-loader 15 }, 16 }, 17 "postcss-loader", 18 "sass-loader", 19 ], 20 }, 21 ], 22 }, 23};
This may change in the future when the module system (i. e. webpack) supports loader matching by origin.
sourceMap
Type:
1type sourceMap = boolean;
Default: depends on the compiler.devtool
value
By default generation of source maps depends on the devtool
option. All values enable source map generation except eval
and false
value.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 sourceMap: true, 9 }, 10 }, 11 ], 12 }, 13};
esModule
Type:
1type esModule = boolean;
Default: true
By default, css-loader
generates JS modules that use the ES modules syntax.
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.
You can enable a CommonJS modules syntax using:
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 esModule: false, 9 }, 10 }, 11 ], 12 }, 13};
exportType
Type:
1type exportType = "array" | "string" | "css-style-sheet";
Default: 'array'
Allows exporting styles as array with modules, string or constructable stylesheet (i.e. CSSStyleSheet
).
Default value is 'array'
, i.e. loader exports array of modules with specific API which is used in style-loader
or other.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 assert: { type: "css" }, 6 loader: "css-loader", 7 options: { 8 exportType: "css-style-sheet", 9 }, 10 }, 11 ], 12 }, 13};
src/index.js
1import sheet from "./styles.css" assert { type: "css" }; 2 3document.adoptedStyleSheets = [sheet]; 4shadowRoot.adoptedStyleSheets = [sheet];
'array'
The default export is array of modules with specific API which is used in style-loader
or other.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.(sa|sc|c)ss$/i, 6 use: ["style-loader", "css-loader", "postcss-loader", "sass-loader"], 7 }, 8 ], 9 }, 10};
src/index.js
1// `style-loader` applies styles to DOM 2import "./styles.css";
'string'
[!WARNING]
You should not use
style-loader
ormini-css-extract-plugin
with this value.
[!WARNING]
The
esModule
option should be enabled if you want to use it withCSS modules
, by default for locals will be used named export.
The default export is string
.
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.(sa|sc|c)ss$/i, 6 use: ["css-loader", "postcss-loader", "sass-loader"], 7 }, 8 ], 9 }, 10};
src/index.js
1import sheet from "./styles.css"; 2 3console.log(sheet);
'css-style-sheet'
[!WARNING]
@import
rules not yet allowed, more information
[!WARNING]
You don't need
style-loader
anymore, please remove it.
[!WARNING]
The
esModule
option should be enabled if you want to use it withCSS modules
, by default for locals will be used named export.
[!WARNING]
Source maps are not currently supported in
Chrome
due bug
The default export is a constructable stylesheet (i.e. CSSStyleSheet
).
Useful for custom elements and shadow DOM.
More information:
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 assert: { type: "css" }, 6 loader: "css-loader", 7 options: { 8 exportType: "css-style-sheet", 9 }, 10 }, 11 12 // For Sass/SCSS: 13 // 14 // { 15 // assert: { type: "css" }, 16 // rules: [ 17 // { 18 // loader: "css-loader", 19 // options: { 20 // exportType: "css-style-sheet", 21 // // Other options 22 // }, 23 // }, 24 // { 25 // loader: "sass-loader", 26 // options: { 27 // // Other options 28 // }, 29 // }, 30 // ], 31 // }, 32 ], 33 }, 34};
src/index.js
1// Example for Sass/SCSS: 2// import sheet from "./styles.scss" assert { type: "css" }; 3 4// Example for CSS modules: 5// import sheet, { myClass } from "./styles.scss" assert { type: "css" }; 6 7// Example for CSS: 8import sheet from "./styles.css" assert { type: "css" }; 9 10document.adoptedStyleSheets = [sheet]; 11shadowRoot.adoptedStyleSheets = [sheet];
For migration purposes, you can use the following configuration:
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 oneOf: [ 7 { 8 assert: { type: "css" }, 9 loader: "css-loader", 10 options: { 11 exportType: "css-style-sheet", 12 // Other options 13 }, 14 }, 15 { 16 use: [ 17 "style-loader", 18 { 19 loader: "css-loader", 20 options: { 21 // Other options 22 }, 23 }, 24 ], 25 }, 26 ], 27 }, 28 ], 29 }, 30};
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.
This can be achieved by using the mini-css-extract-plugin, because it creates separate css files.
For development
mode (including webpack-dev-server
) you can use style-loader, because it injects CSS into the DOM using multiple <style></style>
and works faster.
[!NOTE]
Do not use
style-loader
andmini-css-extract-plugin
together.
webpack.config.js
1const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 2const devMode = process.env.NODE_ENV !== "production"; 3 4module.exports = { 5 module: { 6 rules: [ 7 { 8 // If you enable `experiments.css` or `experiments.futureDefaults`, please uncomment line below 9 // type: "javascript/auto", 10 test: /\.(sa|sc|c)ss$/i, 11 use: [ 12 devMode ? "style-loader" : MiniCssExtractPlugin.loader, 13 "css-loader", 14 "postcss-loader", 15 "sass-loader", 16 ], 17 }, 18 ], 19 }, 20 plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]), 21};
/* webpackIgnore: true */
commentWith the help of the /* webpackIgnore: true */
comment, it is possible to disable sources handling for rules and for individual declarations.
1/* webpackIgnore: true */ 2@import url(./basic.css); 3@import /* webpackIgnore: true */ url(./imported.css); 4 5.class { 6 /* Disabled url handling for the all urls in the 'background' declaration */ 7 color: red; 8 /* webpackIgnore: true */ 9 background: url("./url/img.png"), url("./url/img.png"); 10} 11 12.class { 13 /* Disabled url handling for the first url in the 'background' declaration */ 14 color: red; 15 background: 16 /* webpackIgnore: true */ url("./url/img.png"), url("./url/img.png"); 17} 18 19.class { 20 /* Disabled url handling for the second url in the 'background' declaration */ 21 color: red; 22 background: 23 url("./url/img.png"), 24 /* webpackIgnore: true */ url("./url/img.png"); 25} 26 27/* prettier-ignore */ 28.class { 29 /* Disabled url handling for the second url in the 'background' declaration */ 30 color: red; 31 background: url("./url/img.png"), 32 /* webpackIgnore: true */ 33 url("./url/img.png"); 34} 35 36/* prettier-ignore */ 37.class { 38 /* Disabled url handling for third and sixth urls in the 'background-image' declaration */ 39 background-image: image-set( 40 url(./url/img.png) 2x, 41 url(./url/img.png) 3x, 42 /* webpackIgnore: true */ url(./url/img.png) 4x, 43 url(./url/img.png) 5x, 44 url(./url/img.png) 6x, 45 /* webpackIgnore: true */ 46 url(./url/img.png) 7x 47 ); 48}
The following webpack.config.js
can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts as Data URLs and copy larger files to the output directory.
For webpack v5:
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 use: ["style-loader", "css-loader"], 7 }, 8 { 9 test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i, 10 // More information here https://webpack.js.org/guides/asset-modules/ 11 type: "asset", 12 }, 13 ], 14 }, 15};
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.
This can be achieved by using the mini-css-extract-plugin to extract the CSS when running in production mode.
As an alternative, if seeking better development performance and css outputs that mimic production. 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
When you have pure CSS (without CSS modules), CSS modules and PostCSS in your project you can use this setup:
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 // For pure CSS - /\.css$/i, 6 // For Sass/SCSS - /\.((c|sa|sc)ss)$/i, 7 // For Less - /\.((c|le)ss)$/i, 8 test: /\.((c|sa|sc)ss)$/i, 9 use: [ 10 "style-loader", 11 { 12 loader: "css-loader", 13 options: { 14 // 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 15 // If you need run `sass-loader` and `postcss-loader` on each CSS `@import` please set it to `2` 16 importLoaders: 1, 17 }, 18 }, 19 { 20 loader: "postcss-loader", 21 options: { plugins: () => [postcssPresetEnv({ stage: 0 })] }, 22 }, 23 // Can be `less-loader` 24 { 25 loader: "sass-loader", 26 }, 27 ], 28 }, 29 // For webpack v5 30 { 31 test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i, 32 // More information here https://webpack.js.org/guides/asset-modules/ 33 type: "asset", 34 }, 35 ], 36 }, 37};
index.css
1.class { 2 background: url(/assets/unresolved/img.png); 3}
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 use: ["style-loader", "css-loader"], 7 }, 8 ], 9 }, 10 resolve: { 11 alias: { 12 "/assets/unresolved/img.png": path.resolve( 13 __dirname, 14 "assets/real-path-to-img/img.png", 15 ), 16 }, 17 }, 18};
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 { 5 test: /\.css$/i, 6 loader: "css-loader", 7 options: { 8 modules: { 9 namedExport: true, 10 exportLocalsConvention: function (name) { 11 return name.replace(/-/g, "_"); 12 }, 13 }, 14 }, 15 }, 16 ], 17 }, 18};
Interoperable CSS
-only and CSS Module
featuresThe 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.
Meanwhile all files matching *.module.scss
are treated as CSS Modules
in this example.
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).
webpack.config.js
1module.exports = { 2 module: { 3 rules: [ 4 // ... 5 // -------- 6 // SCSS ALL EXCEPT MODULES 7 { 8 test: /\.scss$/i, 9 exclude: /\.module\.scss$/i, 10 use: [ 11 { 12 loader: "style-loader", 13 }, 14 { 15 loader: "css-loader", 16 options: { 17 importLoaders: 1, 18 modules: { 19 mode: "icss", 20 }, 21 }, 22 }, 23 { 24 loader: "sass-loader", 25 }, 26 ], 27 }, 28 // -------- 29 // SCSS MODULES 30 { 31 test: /\.module\.scss$/i, 32 use: [ 33 { 34 loader: "style-loader", 35 }, 36 { 37 loader: "css-loader", 38 options: { 39 importLoaders: 1, 40 modules: { 41 mode: "local", 42 }, 43 }, 44 }, 45 { 46 loader: "sass-loader", 47 }, 48 ], 49 }, 50 // -------- 51 // ... 52 ], 53 }, 54};
variables.scss
File treated as ICSS
-only.
1$colorBackground: red; 2:export { 3 colorBackgroundCanvas: $colorBackground; 4}
Component.module.scss
File treated as CSS Module
.
1@import "variables.scss"; 2.componentClass { 3 background-color: $colorBackground; 4}
Component.jsx
Using both CSS Module
functionality as well as SCSS variables directly in JavaScript.
1import * as svars from "variables.scss"; 2import * as styles from "Component.module.scss"; 3 4// Render DOM with CSS modules class name 5// <div className={styles.componentClass}> 6// <canvas ref={mountsCanvas}/> 7// </div> 8 9// Somewhere in JavaScript canvas drawing code use the variable directly 10// const ctx = mountsCanvas.current.getContext('2d',{alpha: false}); 11ctx.fillStyle = `${svars.colorBackgroundCanvas}`;
Please take a moment to read our contributing guidelines if you haven't yet done so.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
2 existing vulnerabilities detected
Details
Reason
4 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 4
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
Found 8/23 approved changesets -- score normalized to 3
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More