Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

CSS Loader

License

NotificationsYou must be signed in to change notification settings

webpack-contrib/css-loader

Repository files navigation

npmnodetestscoveragediscussionsize

css-loader

Thecss-loader interprets@import andurl() likeimport/require() and resolves them.

Getting Started

Warning

To use the latest version of css-loader, webpack@5 is required

To begin, you'll need to installcss-loader:

npm install --save-dev css-loader

or

yarn add -D css-loader

or

pnpm add -D css-loader

Then, add the loader to yourwebpack configuration. For example:

file.js

import*ascssfrom"file.css";

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,use:["style-loader","css-loader"],},],},};

Finally, runwebpack using the method you normally use (e.g., via CLI or an npm script).

If you need to extract CSS into a separate file (i.e. do not store CSS in a JS module), consider using therecommend example.

Options

url

Type:

typeurl=|boolean|{filter:(url:string,resourcePath:string)=>boolean;};

Default:true

Enables or disables handling the CSS functionsurl andimage-set.

  • If set tofalse,css-loader will not parse any paths specified inurl orimage-set.
  • You can also pass a function to control this behavior dynamically based on the asset path.

As of version4.0.0, absolute paths are resolved based on the server root.

Examples resolutions:

url(image.png)=>require('./image.png')url('image.png')=>require('./image.png')url(./image.png)=>require('./image.png')url('./image.png')=>require('./image.png')url('http://dontwritehorriblecode.com/2112.png')=>require('http://dontwritehorriblecode.com/2112.png')image-set(url('image2x.png')1x,url('image1x.png')2x)=>require('./image1x.png')andrequire('./image2x.png')

To import assets from anode_modules path (includingresolve.modules) or analias, prefix it with a~:

url(~module/image.png)=>require('module/image.png')url('~module/image.png')=>require('module/image.png')url(~aliasDirectory/image.png)=>require('otherDirectory/image.png')

boolean

Enable/disableurl() resolving.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{url:true,},},],},};

object

Allows filtering ofurl() values.

Any filteredurl() will not be resolved (left in the code as they were written).

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{url:{filter:(url,resourcePath)=>{// resourcePath - path to css file// Don't handle `img.png` urlsif(url.includes("img.png")){returnfalse;}// Don't handle images under root-relative /external_images/if(/^\/external_images\//.test(url)){returnfalse;}returntrue;},},},},],},};

import

Type:

typeimportFn=|boolean|{filter:(url:string,media:string,resourcePath:string,supports?:string,layer?:string,)=>boolean;};

Default:true

Allows you to enable or disable handling of@import at-rules.

Controls how@import statements are resolved.

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 anode_modules path (includeresolve.modules) or analias, 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

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{import:true,},},],},};

object

filter

Type:

typefilter=(url:string,media:string,resourcePath:string)=>boolean;

Default:undefined

Allows filtering of@import.

Any filtered@import will not be resolved (left in the code as they were written).

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{import:{filter:(url,media,resourcePath)=>{// resourcePath - path to css file// Don't handle `style.css` importif(url.includes("style.css")){returnfalse;}returntrue;},},},},],},};

modules

Type:

typemodules=|boolean|"local"|"global"|"pure"|"icss"|{auto:boolean|regExp|((resourcePath:string)=>boolean);mode:|"local"|"global"|"pure"|"icss"|((resourcePath)=>"local"|"global"|"pure"|"icss");localIdentName:string;localIdentContext:string;localIdentHashSalt:string;localIdentHashFunction:string;localIdentHashDigest:string;localIdentRegExp:string|regExp;getLocalIdent:(context:LoaderContext,localIdentName:string,localName:string,)=>string;namedExport:boolean;exportGlobals:boolean;exportLocalsConvention:|"as-is"|"camel-case"|"camel-case-only"|"dashes"|"dashes-only"|((name:string)=>string);exportOnlyLocals:boolean;getJSON:({        resourcePath,        imports,        exports,        replacements,}:{resourcePath:string;imports:object[];exports:object[];replacements:object[];})=>Promise<void>|void;};

Default:undefined

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 themode option (seemode for details).
  • object: Enables CSS modules for all files unless themodules.auto option is provided. otherwise themodules.auto option will determine whether if it is CSS Modules or not (seeauto for more details).

Themodules option enables/disables theCSS Modules specification and configures its behavior.

Settingmodules: false can improve performance because we avoid parsingCSS Modules features, this is useful for developers using use vanilla CSS or other technologies.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:true,},},],},};

Features

Scope
  • Usinglocal value requires you to specify:global classes.
  • Usingglobal value requires you to specify:local classes.
  • Usingpure value requires selectors must contain at least one local class or ID.

You can find more information on scoping modulehere.

With CSS Modules, styles are scoped locally, preventing conflicts with global styles.

Use:local(.className) to declare aclassName in the local scope. The local identifiers are exported by the module.

  • With:local (without parentheses) local mode can be switchedon for this selector.
  • The:global(.className) notation can be used to declare an explicit global selector.
  • With:global (without parentheses) global mode can be switchedon for this selector.

The loader replaces local selectors with unique, scoped identifiers. The chosen unique identifiers are exported by the module.

:local(.className) {background: red;}:local .className {color: green;}:local(.className .subClass) {color: green;}:local .className .subClass:global(.global-class-name) {color: blue;}

Output (example):

._23_aKvs-b8bW2Vg3fwHozO {background: red;}._23_aKvs-b8bW2Vg3fwHozO {color: green;}._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 {color: green;}._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name {color: blue;}

Note

Identifiers are exported

exports.locals={className:"_23_aKvs-b8bW2Vg3fwHozO",subClass:"_13LGdX8RMStbBE9w-t0gZ1",};

CamelCase naming is recommended for local selectors, as it simplifies usage in imported JS modules.

Although you can use:local(#someId), but this is not recommended. Prefer classes instead of IDs for modular styling.

Composing

When declaring a local class name, you can compose it from one or more other local class names.

:local(.className) {background: red;color: yellow;}:local(.subClass) {composes: className;background: blue;}

This does not alter the final CSS output, but the generatedsubClass will include both class names in its export.

exports.locals={className:"_23_aKvs-b8bW2Vg3fwHozO",subClass:"_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO",};
._23_aKvs-b8bW2Vg3fwHozO {background: red;color: yellow;}._13LGdX8RMStbBE9w-t0gZ1 {background: blue;}
Importing

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 multiplecomposes: 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.

We recommend following a naming convention:

  • v- prefix for values
  • s- prefix for selectors
  • m- prefix for media at-rules.
@value v-primary:#BF4040;@value s-black: black-selector;@value m-large: (min-width:960px);.header {color: v-primary;padding:010px;}.s-black {color: black;}@media m-large {  .header {padding:020px;  }}

boolean

EnableCSS Modules features.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:true,},},],},};

string

EnableCSS Modules features and setupmode.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{// Using `local` value has same effect like using `modules: true`modules:"global",},},],},};

object

EnableCSS Modules features and configure its behavior throughoptions.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{mode:"local",auto:true,exportGlobals:true,localIdentName:"[path][name]__[local]--[hash:base64:5]",localIdentContext:path.resolve(__dirname,"src"),localIdentHashSalt:"my-custom-hash",namedExport:true,exportLocalsConvention:"as-is",exportOnlyLocals:false,getJSON:({ resourcePath, imports, exports, replacements})=>{},},},},],},};
auto

Type:

typeauto=|boolean|regExp|((resourcePath:string,resourceQuery:string,resourceFragment:string,)=>boolean);

Default:undefined

Allows auto enable CSS modules or ICSS based on the file name, query or fragment whenmodules 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 themodules.mode option tolocal value for all files which satisfy/\.module(s)?\.\w+$/i.test(filename) condition or sets themodules.mode option toicss 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.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{auto:true,},},},],},};
RegExp

Enables CSS modules for files based on the filename satisfying your regex check.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{auto:/\.custom-module\.\w+$/i,},},},],},};
function

Enables CSS Modules for files based on the filename, query or fragment satisfying your filter function check.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{auto:(resourcePath,resourceQuery,resourceFragment)=>{returnresourcePath.endsWith(".custom-module.css");},},},},],},};
mode

Type:

typemode=|"local"|"global"|"pure"|"icss"|((resourcePath:string,resourceQuery:string,resourceFragment:string,)=>"local"|"global"|"pure"|"icss");

Default:'local'

Setupmode option. You can omit the value when you wantlocal mode.

Controls the level of compilation applied to the input styles.

  • Thelocal,global, andpure handlesclass andid scoping and@value values.
  • Theicss will only compile the low levelInteroperable 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.

string

Possible values -local,global,pure, andicss.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{mode:"global",},},},],},};
function

Allows setting different values for themode option based on the filename, query or fragment.Possible return values -local,global,pure andicss.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{// Callback must return "local", "global", or "pure" valuesmode:(resourcePath,resourceQuery,resourceFragment)=>{if(/pure.css$/i.test(resourcePath)){return"pure";}if(/global.css$/i.test(resourcePath)){return"global";}return"local";},},},},],},};
localIdentName

Type:

typelocalIdentName=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 thecompiler.context option ormodules.localIdentContext option.
  • [path] the path of the resource relative to thecompiler.context option ormodules.localIdentContext option.
  • [file] - filename and path.
  • [ext] - extension with leading..
  • [hash] - the hash of the string, generated based onlocalIdentHashSalt,localIdentHashFunction,localIdentHashDigest,localIdentHashDigestLength,localIdentContext,resourcePath andexportName
  • [<hashFunction>:hash:<hashDigest>:<hashDigestLength>] - 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-.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{localIdentName:"[path][name]__[local]--[hash:base64:5]",},},},],},};
localIdentContext

Type:

typelocalIdentContex=string;

Default:compiler.context

Allows redefining the basic loader context for local ident name.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{localIdentContext:path.resolve(__dirname,"src"),},},},],},};
localIdentHashSalt

Type:

typelocalIdentHashSalt=string;

Default:undefined

Allows to add custom hash to generate more unique classes.

For more information seeoutput.hashSalt.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{localIdentHashSalt:"hash",},},},],},};
localIdentHashFunction

Type:

typelocalIdentHashFunction=string;

Default:md4

Allows to specify hash function to generate classes .

For more information seeoutput.hashFunction.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{localIdentHashFunction:"md4",},},},],},};
localIdentHashDigest

Type:

typelocalIdentHashDigest=string;

Default:hex

Allows to specify hash digest to generate classes.

For more information seeoutput.hashDigest.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{localIdentHashDigest:"base64",},},},],},};
localIdentHashDigestLength

Type:

typelocalIdentHashDigestLength=number;

Default:20

Allows to specify hash digest length to generate classes.

For more information, seeoutput.hashDigestLength.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{localIdentHashDigestLength:5,},},},],},};
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

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{hashStrategy:"minimal-subset",},},},],},};
localIdentRegExp

Type:

typelocalIdentRegExp=string|RegExp;

Default:undefined

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{localIdentRegExp:/page-(.*)\.css/i,},},},],},};
getLocalIdent

Type:

typegetLocalIdent=(context:LoaderContext,localIdentName:string,localName:string,)=>string;

Default:undefined

Allows to specify a function to generate the classname.

By default we use built-in function to generate a classname.

If your custom function returnsnull orundefined, the built-in generator is used as afallback.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{getLocalIdent:(context,localIdentName,localName,options)=>{return"whatever_random_class_name";},},},},],},};
namedExport

Type:

typenamedExport=boolean;

Default: Depends on the value of theesModule option. If the value of theesModule options istrue,namedExport defaults totrue ; otherwise, it defaults tofalse.

Enables or disables ES modules named export for locals.

Warning

Thedefault class name cannot be used directly whennamedExport istrue becausedefault is a reserved keyword in ECMAScript modules. It is automatically renamed to_default.

styles.css

.foo-baz {color: red;}.bar {color: blue;}.default {color: green;}

index.js

import*asstylesfrom"./styles.css";// If using `exportLocalsConvention: "as-is"` (default value):console.log(styles["foo-baz"],styles.bar);// If using `exportLocalsConvention: "camel-case-only"`:console.log(styles.fooBaz,styles.bar);// For the `default` classnameconsole.log(styles["_default"]);

You can enable ES module named export using:

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{esModule:true,modules:{namedExport:true,},},},],},};

To set a custom name for namedExport, can useexportLocalsConvention option as a function.

See below in theexamples section.

exportGlobals

Type:

typeexportsGLobals=boolean;

Default:false

Allowcss-loader to export names from global class or ID, so you can use that as local name.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{exportGlobals:true,},},},],},};
exportLocalsConvention

Type:

typeexportLocalsConvention=|"as-is"|"camel-case"|"camel-case-only"|"dashes"|"dashes-only"|((name:string)=>string);

Default: Depends on the value of themodules.namedExport option:

  • Iftrue -as-is
  • Otherwisecamel-case-only (class names converted to camelCase, original name removed).

Warning

Names of locals are converted to camelCase when the named export isfalse, 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.eas-is value).

NameTypeDescription
'as-is'stringClass names will be exported as is.
'camel-case'stringClass names will be camelCased, but the original class name will not to be removed from the locals.
'camel-case-only'stringClass names will be camelCased, and original class name will be removed from the locals.
'dashes'stringOnly dashes in class names will be camelCased
'dashes-only'stringDashes in class names will be camelCased, the original class name will be removed from the locals

file.css

.class-name {}

file.js

import{className}from"file.css";

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{exportLocalsConvention:"camel-case-only",},},},],},};
function

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{exportLocalsConvention:function(name){returnname.replace(/-/g,"_");},},},},],},};

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{exportLocalsConvention:function(name){return[name.replace(/-/g,"_"),// dashesCamelCasename.replace(/-+(\w)/g,(match,firstLetter)=>firstLetter.toUpperCase(),),];},},},},],},};
exportOnlyLocals

Type:

typeexportOnlyLocals=boolean;

Default:false

Export only locals.

Useful when you usecss modules for pre-rendering (for example SSR).

For pre-rendering withmini-css-extract-plugin you should use this option instead ofstyle-loader!css-loaderin the pre-rendering bundle.

It doesn't embed CSS; it only exports the identifier mappings.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{exportOnlyLocals:true,},},},],},};
getJSON

Type:

typegetJSON=({  resourcePath,  imports,  exports,  replacements,}:{resourcePath:string;imports:object[];exports:object[];replacements:object[];})=>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.,

[  {"type":"icss_import","importName":"___CSS_LOADER_ICSS_IMPORT_0___","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\"","icss":true,"index":0  }]

(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.,
[  {"name":"main","value":"D2Oy"  }]
  • replacements: an array of import replacement objects used for linkingimports andexports, e.g.,
{"replacementName":"___CSS_LOADER_ICSS_IMPORT_0_REPLACEMENT_0___","importName":"___CSS_LOADER_ICSS_IMPORT_0___","localName":"main"}

UsinggetJSON, it's possible to output a file with all CSS module mappings.

In the following example, we usegetJSON to cache canonical mappings and add stand-ins for any composed values (throughcomposes), and we use a custom plugin to consolidate the values and output them to a file:

webpack.config.js

constpath=require("path");constfs=require("fs");constCSS_LOADER_REPLACEMENT_REGEX=/(___CSS_LOADER_ICSS_IMPORT_\d+_REPLACEMENT_\d+___)/g;constREPLACEMENT_REGEX=/___REPLACEMENT\[(.*?)]\[(.*?)]___/g;constIDENTIFIER_REGEX=/\[(.*?)]\[(.*?)]/;constreplacementsMap={};constcanonicalValuesMap={};constallExportsJson={};functiongenerateIdentifier(resourcePath,localName){return`[${resourcePath}][${localName}]`;}functionaddReplacements(resourcePath,imports,exportsJson,replacements){constimportReplacementsMap={};// 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[<absolute_path>][<class_name>]___')// to be replaced in the plugin belowfor(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 laterreplacementsMap[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 verbatimcanonicalValuesMap[identifier]=classNames;allExportsJson[resourcePath]=allExportsJson[resourcePath]||{};allExportsJson[resourcePath][localName]=classNames;}}}functionreplaceReplacements(classNames){returnclassNames.replaceAll(REPLACEMENT_REGEX,(_,resourcePath,localName)=>{constidentifier=generateIdentifier(resourcePath,localName);if(identifierincanonicalValuesMap){returncanonicalValuesMap[identifier];}// Recurse through other stand-in that may be importsconstcanonicalValue=replaceReplacements(replacementsMap[identifier]);canonicalValuesMap[identifier]=canonicalValue;returncanonicalValue;},);}functiongetJSON({ resourcePath, imports, exports, replacements}){constexportsJson=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 belowaddReplacements(resourcePath,imports,exportsJson,replacements);}else{// no replacements present --> add to canonicalValuesMap verbatim// since all values here are canonical/don't need resolutionfor(const[key,value]ofObject.entries(exportsJson)){constid=`[${resourcePath}][${key}]`;canonicalValuesMap[id]=value;}allExportsJson[resourcePath]=exportsJson;}}classCssModulesJsonPlugin{constructor(options){this.options=options;}// eslint-disable-next-line class-methods-use-thisapply(compiler){compiler.hooks.emit.tap("CssModulesJsonPlugin",()=>{for(const[identifier,classNames]ofObject.entries(replacementsMap)){constadjustedClassNames=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,"/");returnkey;}),),null,2,),"utf8",);});}}module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{ getJSON}},},],},plugins:[newCssModulesJsonPlugin({filepath:path.resolve(__dirname,"./output.css.json"),}),],};

In the above, all import aliases are replaced with___REPLACEMENT[<resourcePath>][<localName>]___ ingetJSON, and they're resolved in the custom plugin. All CSS mappings are contained inallExportsJson:

{"foo/bar/baz.module.css": {"main":"D2Oy","header":"thNN"  },"foot/bear/bath.module.css": {"logo":"sqiR","info":"XMyI"  }}

This is saved to a local file namedoutput.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 optionimportLoaders allows you to configure how many loaders beforecss-loader should be applied to@imported resources and CSS Modules/ICSS imports.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,use:["style-loader",{loader:"css-loader",options:{importLoaders:2,// 0 => no loaders (default);// 1 => postcss-loader;// 2 => postcss-loader, sass-loader},},"postcss-loader","sass-loader",],},],},};

This may change in the future when the module system (i. e. webpack) supports loader matching by origin.

sourceMap

Type:

typesourceMap=boolean;

Default: depends on thecompiler.devtool value

By default generation of source maps depends on thedevtool option. All values enable source map generation excepteval andfalse values.

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{sourceMap:true,},},],},};

esModule

Type:

typeesModule=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 ofmodule concatenation andtree shaking.

You can enable CommonJS module syntax using:

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{esModule:false,},},],},};

exportType

Type:

typeexportType="array"|"string"|"css-style-sheet";

Default:'array'

Allows exporting styles as array with modules, string orconstructable stylesheet (i.e.CSSStyleSheet).

The default value is'array', i.e. loader exports an array of modules with a specific API which is used instyle-loader or other.

webpack.config.js

module.exports={module:{rules:[{assert:{type:"css"},loader:"css-loader",options:{exportType:"css-style-sheet",},},],},};

src/index.js

importsheetfrom"./styles.css"assert{type: "css"};document.adoptedStyleSheets=[sheet];shadowRoot.adoptedStyleSheets=[sheet];

'array'

The default export is array of modules with specific API which is used instyle-loader or other.

webpack.config.js

module.exports={module:{rules:[{test:/\.(sa|sc|c)ss$/i,use:["style-loader","css-loader","postcss-loader","sass-loader"],},],},};

src/index.js

// `style-loader` applies styles to DOMimport"./styles.css";

'string'

Warning

You should not usestyle-loader ormini-css-extract-plugin with this value.

TheesModule option should be enabled if you want to use it withCSS modules. By default for localsnamed export will be used.

The default export isstring.

webpack.config.js

module.exports={module:{rules:[{test:/\.(sa|sc|c)ss$/i,use:["css-loader","postcss-loader","sass-loader"],},],},};

src/index.js

importsheetfrom"./styles.css";console.log(sheet);

'css-style-sheet'

Warning

@import rules not yet allowed, moreinformation

Warning

You don't needstyle-loader anymore, please remove it.

Warning

TheesModule option should be enabled if you want to use it withCSS modules. By default for localsnamed export will be used.

Warning

Source maps are not currently supported inChrome due to abug

The default export is aconstructable stylesheet (i.e.CSSStyleSheet).

Useful forcustom elements and shadow DOM.

More information:

webpack.config.js

module.exports={module:{rules:[{assert:{type:"css"},loader:"css-loader",options:{exportType:"css-style-sheet",},},// For Sass/SCSS://// {//   assert: { type: "css" },//   rules: [//     {//       loader: "css-loader",//       options: {//         exportType: "css-style-sheet",//         // Other options//       },//     },//     {//       loader: "sass-loader",//       options: {//         // Other options//       },//     },//   ],// },],},};

src/index.js

// Example for Sass/SCSS:// import sheet from "./styles.scss" assert { type: "css" };// Example for CSS modules:// import sheet, { myClass } from "./styles.scss" assert { type: "css" };// Example for CSS:importsheetfrom"./styles.css"assert{type: "css"};document.adoptedStyleSheets=[sheet];shadowRoot.adoptedStyleSheets=[sheet];

For migration purposes, you can use the following configuration:

module.exports={module:{rules:[{test:/\.css$/i,oneOf:[{assert:{type:"css"},loader:"css-loader",options:{exportType:"css-style-sheet",// Other options},},{use:["style-loader",{loader:"css-loader",options:{// Other options},},],},],},],},};

Examples

Recommend

Forproduction 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 themini-css-extract-plugin, because it creates separate css files.

Fordevelopment mode (includingwebpack-dev-server) you can usestyle-loader, because it injects CSS into the DOM using multiple<style></style> and works faster.

Note

Do not usestyle-loader andmini-css-extract-plugin together.

webpack.config.js

constMiniCssExtractPlugin=require("mini-css-extract-plugin");constdevMode=process.env.NODE_ENV!=="production";module.exports={module:{rules:[{// If you enable `experiments.css` or `experiments.futureDefaults`, please uncomment line below// type: "javascript/auto",test:/\.(sa|sc|c)ss$/i,use:[devMode ?"style-loader" :MiniCssExtractPlugin.loader,"css-loader","postcss-loader","sass-loader",],},],},plugins:[].concat(devMode ?[] :[newMiniCssExtractPlugin()]),};

Disable URL resolving using the/* webpackIgnore: true */ comment

With the help of the/* webpackIgnore: true */comment, it is possible to disable sources handling for rules and for individual declarations.

/* webpackIgnore: true */@import url(./basic.css);@import/* webpackIgnore: true */ url(./imported.css);.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 followingwebpack.config.js can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts asData 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 themini-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

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",},],},};

Resolve unresolved URLs using an alias

index.css

.class {background:url(/assets/unresolved/img.png);}

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,use:["style-loader","css-loader"],},],},resolve:{alias:{"/assets/unresolved/img.png":path.resolve(__dirname,"assets/real-path-to-img/img.png",),},},};

Named export with custom export names

webpack.config.js

module.exports={module:{rules:[{test:/\.css$/i,loader:"css-loader",options:{modules:{namedExport:true,exportLocalsConvention:function(name){returnname.replace(/-/g,"_");},},},},],},};

SeparatingInteroperable CSS-only andCSS Module features

The following setup is an example of allowingInteroperable CSS features only (such as:import and:export) without using furtherCSS Module functionality by setting themode option for all files that do not match the*.module.scss naming convention. This is for reference, as havingICSS features applied to all files was defaultcss-loader behavior before v4.

Meanwhile, all files matching*.module.scss are treated asCSS 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

module.exports={module:{rules:[// ...// --------// SCSS ALL EXCEPT MODULES{test:/\.scss$/i,exclude:/\.module\.scss$/i,use:[{loader:"style-loader",},{loader:"css-loader",options:{importLoaders:1,modules:{mode:"icss",},},},{loader:"sass-loader",},],},// --------// SCSS MODULES{test:/\.module\.scss$/i,use:[{loader:"style-loader",},{loader:"css-loader",options:{importLoaders:1,modules:{mode:"local",},},},{loader:"sass-loader",},],},// --------// ...],},};

variables.scss

File treated asICSS-only.

$colorBackground:red;:export {colorBackgroundCanvas:$colorBackground;}

Component.module.scss

File treated asCSS Module.

@import"variables.scss";.componentClass {background-color:$colorBackground;}

Component.jsx

Using bothCSS Module functionality as well as SCSS variables directly in JavaScript.

import*assvarsfrom"variables.scss";import*asstylesfrom"Component.module.scss";// Render DOM with CSS modules class name// <div className={styles.componentClass}>//   <canvas ref={mountsCanvas}/>// </div>// Somewhere in JavaScript canvas drawing code use the variable directly// const ctx = mountsCanvas.current.getContext('2d',{alpha: false});ctx.fillStyle=`${svars.colorBackgroundCanvas}`;

Contributing

We welcome all contributions!

If you are new here, please take a moment to review our contributing guidelines before submitting issues or pull requests.

CONTRIBUTING

License

MIT

Sponsor this project

    Packages

    No packages published

    Contributors124


    [8]ページ先頭

    ©2009-2025 Movatter.jp