You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Allows you to enable or disable CSS Modules or ICSS and configure them:
undefined: Enables CSS modules for all files matching /\.module\.\w+$/i.test(filename) or /\.icss\.\w+$/i.test(filename) regexp.
true: Enables CSS modules for all files.
false: Disables CSS Modules for all files.
string: Disables CSS Modules for all files and set the mode option (see mode for details).
object: Enables CSS modules for all files unless the modules.auto option is provided. otherwise the modules.auto option will determine whether if it is CSS Modules or not (see auto for more details).
The modules option enables/disables the CSS Modules specification and configures its behavior.
Setting modules: false can improve performance because we avoid parsing CSS Modules features, this is useful for developers using use vanilla CSS or other technologies.
To import a local class names from another module.
Note
It is highly recommended to include file extensions 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.
:local(.continueButton) { composes: button from "library/button.css"; background: red; }
:local(.nameEdit) { composes: edit highlight from "./edit.css"; background: red; }
To import from multiple modules use multiple composes: rules.
:local(.className) { composes: edit highlight from "./edit.css", button from "module/button.css", classFromThisModule; background: red; }
or
:local(.className) { composes: edit highlight from "./edit.css"; composes: button from "module/button.css"; composes: classFromThisModule; background: red; }
Values
You can use @value to specific values to be reused throughout a document.
module.exports={ module: { rules: [ { test: /\.css$/i, loader: "css-loader", options: { // Using `local` value has same effect like using `modules: true` modules: "global", }, }, ], }, };
object
Enable CSS Modules features and configure its behavior through options.
Allows auto enable CSS modules or ICSS based on the file name, query or fragment when modules option is an object.
Possible values:
undefined: Enables CSS modules for all files.
true: Enables CSS modules for files matching /\.module\.\w+$/i.test(filename) and /\.icss\.\w+$/i.test(filename) regexp.
false: Disables CSS Modules for all files.
RegExp: Enables CSS modules for all files matching /RegExp/i.test(filename) regexp.
function: Enables CSS Modules for files based on the file name satisfying your filter function check.
boolean
Possible values:
true: Enables CSS modules or Interoperable CSS (ICSS) 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) condition.
false: Disables CSS modules or ICSS format based on filename for all files.
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 (ICSS) 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.
[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
[:hash::] - hash with hash settings.
[local] - original class.
Recommendations:
Use '[path][name]__[local]' for development
Use '[hash:base64]' for production
The [local] placeholder contains original class.
Note: all reserved characters (<>:"/\|?*) and control filesystem characters (excluding characters in the [local] placeholder) will be converted to -.
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.
Default: Depends on the value of the esModule option. If the value of the esModule options is true, namedExport defaults to true ; otherwise, it defaults to false.
Enables or disables ES modules named export for locals.
Warning
The default class name cannot be used directly when namedExport is true because default is a reserved keyword in ECMAScript modules. It is automatically renamed to _default.
Default: Depends on the value of the modules.namedExport option:
If true - as-is
Otherwise camel-case-only (class names converted to camelCase, original name removed).
Warning
Names of locals are converted to camelCase when the named export is false, i.e. the exportLocalsConvention 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 camelCased, but the original class name will not to be removed from the locals.
'camel-case-only'
string
Class names will be camelCased, and original class name will be removed from the locals.
'dashes'
string
Only dashes in class names will be camelCased
'dashes-only'
string
Dashes in class names will be camelCased, the original class name will be removed from the locals
Using getJSON, it's possible to output a file 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
{
const replacementImportUrl = imports.find(
(importData) => importData.importName === importName,
).url;
const relativePathRe = /.*!(.*)"/;
const [, relativePath] = replacementImportUrl.match(relativePathRe);
const importPath = path.resolve(path.dirname(resourcePath), relativePath);
const identifier = generateIdentifier(importPath, localName);
return { ...acc, [replacementName]: `___REPLACEMENT${identifier}___` };
},
{},
);
// iterate through the raw exports and add stand-in variables
// ('___REPLACEMENT[][]___')
// to be replaced in the plugin below
for (const [localName, classNames] of Object.entries(exportsJson)) {
const identifier = generateIdentifier(resourcePath, localName);
if (CSS_LOADER_REPLACEMENT_REGEX.test(classNames)) {
// if there are any replacements needed in the concatenated class names,
// add them all to the replacements map to be replaced altogether later
replacementsMap[identifier] = classNames.replaceAll(
CSS_LOADER_REPLACEMENT_REGEX,
(_, replacementName) =>
importReplacementsMap[resourcePath][replacementName],
);
} else {
// otherwise, no class names need replacements so we can add them to
// canonical values map and all exports JSON verbatim
canonicalValuesMap[identifier] = classNames;
allExportsJson[resourcePath] = allExportsJson[resourcePath] || {};
allExportsJson[resourcePath][localName] = classNames;
}
}
}
function replaceReplacements(classNames) {
return classNames.replaceAll(
REPLACEMENT_REGEX,
(_, resourcePath, localName) => {
const identifier = generateIdentifier(resourcePath, localName);
if (identifier in canonicalValuesMap) {
return canonicalValuesMap[identifier];
}
// Recurse through other stand-in that may be imports
const canonicalValue = replaceReplacements(replacementsMap[identifier]);
canonicalValuesMap[identifier] = canonicalValue;
return canonicalValue;
},
);
}
function getJSON({ resourcePath, imports, exports, replacements }) {
const exportsJson = exports.reduce((acc, { name, value }) => {
return { ...acc, [name]: value };
}, {});
if (replacements.length > 0) {
// replacements present --> add stand-in values for absolute paths and local names,
// which will be resolved to their canonical values in the plugin below
addReplacements(resourcePath, imports, exportsJson, replacements);
} else {
// no replacements present --> add to canonicalValuesMap verbatim
// since all values here are canonical/don't need resolution
for (const [key, value] of Object.entries(exportsJson)) {
const id = `[${resourcePath}][${key}]`;
canonicalValuesMap[id] = value;
}
allExportsJson[resourcePath] = exportsJson;
}
}
class CssModulesJsonPlugin {
constructor(options) {
this.options = options;
}
// eslint-disable-next-line class-methods-use-this
apply(compiler) {
compiler.hooks.emit.tap("CssModulesJsonPlugin", () => {
for (const [identifier, classNames] of Object.entries(replacementsMap)) {
const adjustedClassNames = replaceReplacements(classNames);
replacementsMap[identifier] = adjustedClassNames;
const [, resourcePath, localName] = identifier.match(IDENTIFIER_REGEX);
allExportsJson[resourcePath] = allExportsJson[resourcePath] || {};
allExportsJson[resourcePath][localName] = adjustedClassNames;
}
fs.writeFileSync(
this.options.filepath,
JSON.stringify(
// Make path to be relative to `context` (your project root)
Object.fromEntries(
Object.entries(allExportsJson).map((key) => {
key[0] = path
.relative(compiler.context, key[0])
.replace(/\\/g, "/");
return key;
}),
),
null,
2,
),
"utf8",
);
});
}
}
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: { modules: { getJSON } },
},
],
},
plugins: [
new CssModulesJsonPlugin({
filepath: path.resolve(__dirname, "./output.css.json"),
}),
],
};">constpath=require("path"); constfs=require("fs");
// create a dict to quickly identify imports and get their absolute stand-in strings in the currently loaded file // e.g., { '___CSS_LOADER_ICSS_IMPORT_0_REPLACEMENT_0___': '___REPLACEMENT[/foo/bar/baz.css][main]___' } importReplacementsMap[resourcePath]=replacements.reduce( (acc,{ replacementName, importName, localName })=>{ constreplacementImportUrl=imports.find( (importData)=>importData.importName===importName, ).url; constrelativePathRe=/.*!(.*)"/; const[,relativePath]=replacementImportUrl.match(relativePathRe); constimportPath=path.resolve(path.dirname(resourcePath),relativePath); constidentifier=generateIdentifier(importPath,localName); return{ ...acc,[replacementName]: `___REPLACEMENT${identifier}___`}; }, {}, );
// iterate through the raw exports and add stand-in variables // ('___REPLACEMENT[][]___') // to be replaced in the plugin below for(const[localName,classNames]ofObject.entries(exportsJson)){ constidentifier=generateIdentifier(resourcePath,localName);
if(CSS_LOADER_REPLACEMENT_REGEX.test(classNames)){ // if there are any replacements needed in the concatenated class names, // add them all to the replacements map to be replaced altogether later replacementsMap[identifier]=classNames.replaceAll( CSS_LOADER_REPLACEMENT_REGEX, (_,replacementName)=> importReplacementsMap[resourcePath][replacementName], ); }else{ // otherwise, no class names need replacements so we can add them to // canonical values map and all exports JSON verbatim canonicalValuesMap[identifier]=classNames;
if(replacements.length>0){ // replacements present --> add stand-in values for absolute paths and local names, // which will be resolved to their canonical values in the plugin below addReplacements(resourcePath,imports,exportsJson,replacements); }else{ // no replacements present --> add to canonicalValuesMap verbatim // since all values here are canonical/don't need resolution for(const[key,value]ofObject.entries(exportsJson)){ constid=`[${resourcePath}][${key}]`;
fs.writeFileSync( this.options.filepath, JSON.stringify( // Make path to be relative to `context` (your project root) Object.fromEntries( Object.entries(allExportsJson).map((key)=>{ key[0]=path .relative(compiler.context,key[0]) .replace(/\\/g,"/");
In the above, all import aliases are replaced with ___REPLACEMENT[][]___ in getJSON, and they're resolved in the custom plugin. All CSS mappings are contained in allExportsJson:
This is saved to a local file named output.css.json.
importLoaders
Type:
typeimportLoaders=number;
Default: 0
Allows to enables/disables or sets up the 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 @imported resources and CSS Modules/ICSS imports.
.class { /* Disabled url handling for the all urls in the 'background' declaration */ color: red; /* webpackIgnore: true */ background:url("./url/img.png"),url("./url/img.png"); }
.class { /* Disabled url handling for the first url in the 'background' declaration */ color: red; background: /* webpackIgnore: true */url("./url/img.png"),url("./url/img.png"); }
.class { /* Disabled url handling for the second url in the 'background' declaration */ color: red; background: url("./url/img.png"), /* webpackIgnore: true */url("./url/img.png"); }
/* prettier-ignore */ .class { /* Disabled url handling for the second url in the 'background' declaration */ color: red; background:url("./url/img.png"), /* webpackIgnore: true */ url("./url/img.png"); }
/* prettier-ignore */ .class { /* Disabled url handling for third and sixth urls in the 'background-image' declaration */ background-image:image-set( url(./url/img.png) 2x, url(./url/img.png) 3x, /* webpackIgnore: true */ url(./url/img.png) 4x, url(./url/img.png) 5x, url(./url/img.png) 6x, /* webpackIgnore: true */ url(./url/img.png) 7x ); }
Assets
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
module.exports={ module: { rules: [ { test: /\.css$/i, use: ["style-loader","css-loader"], }, { test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i, // More information here https://webpack.js.org/guides/asset-modules/ type: "asset", }, ], }, };
Extract
For production builds it's recommended to extract the CSS from your bundle to enable 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.
Pure CSS, CSS Modules and PostCSS
When you have pure CSS (without CSS modules), CSS modules and PostCSS in your project, you can use this setup:
webpack.config.js
[postcssPresetEnv({ stage: 0 })] },
},
// Can be `less-loader`
{
loader: "sass-loader",
},
],
},
// For webpack v5
{
test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
// More information here https://webpack.js.org/guides/asset-modules/
type: "asset",
},
],
},
};">module.exports={ module: { rules: [ { // For pure CSS - /\.css$/i, // For Sass/SCSS - /\.((c|sa|sc)ss)$/i, // For Less - /\.((c|le)ss)$/i, test: /\.((c|sa|sc)ss)$/i, use: [ "style-loader", { loader: "css-loader", options: { // 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 // If you need run `sass-loader` and `postcss-loader` on each CSS `@import` please set it to `2` importLoaders: 1, }, }, { loader: "postcss-loader", options: {plugins: ()=>[postcssPresetEnv({stage: 0})]}, }, // Can be `less-loader` { loader: "sass-loader", }, ], }, // For webpack v5 { test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i, // More information here https://webpack.js.org/guides/asset-modules/ type: "asset", }, ], }, };
Separating Interoperable CSS-only and CSS Module features
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 the mode option for all files that do not match the *.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).