Hướng dẫn css-loader github
The Warning To use css-loader, webpack@5 is required To begin, you'll need to install or or Then add the plugin to your file.js import css from "file.css"; webpack.config.js module.exports = { module: { rules: [ { test: /\.css$/i, use: ["style-loader", "css-loader"], }, ], }, }; And run 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. Options
|
Name | Type | Description |
---|---|---|
'asIs'
| string
| Class names will be exported as is. |
'camelCase'
| string
| Class names will be camelized, the original class name will not to be removed from the locals |
'camelCaseOnly'
| 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 |
'dashesOnly'
| string
| Dashes in class names will be camelized, the original class name will be removed from the locals |
file.css
file.js
import { className } from "file.css";
webpack.config.js
module.exports = { module: { rules: [ { test: /\.css$/i, loader: "css-loader", options: { modules: { exportLocalsConvention: "camelCase", }, }, }, ], }, };
function
webpack.config.js
module.exports = { module: { rules: [ { test: /\.css$/i, loader: "css-loader", options: { modules: { exportLocalsConvention: function (name) { return name.replace(/-/g, "_"); }, }, }, }, ], }, };
webpack.config.js
module.exports = { module: { rules: [ { test: /\.css$/i, loader: "css-loader", options: { modules: { exportLocalsConvention: function (name) { return [ name.replace(/-/g, "_"), // dashesCamelCase name.replace(/-+(\w)/g, (match, firstLetter) => firstLetter.toUpperCase() ), ]; }, }, }, }, ], }, };
exportOnlyLocals
Type:
type 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
module.exports = { module: { rules: [ { test: /\.css$/i, loader: "css-loader", options: { modules: { exportOnlyLocals: true, }, }, }, ], }, };
importLoaders
Type:
type 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
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:
type 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
module.exports = { module: { rules: [ { test: /\.css$/i, loader: "css-loader", options: { sourceMap: true, }, }, ], }, };
esModule
Type:
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
module.exports = { module: { rules: [ { test: /\.css$/i, loader: "css-loader", options: { esModule: false, }, }, ], }, };
exportType
Type:
type 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
module.exports = { module: { rules: [ { assert: { type: "css" }, loader: "css-loader", options: { exportType: "css-style-sheet", }, }, ], }, };
src/index.js
import sheet from "./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 in style-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 DOM import "./styles.css";
'string'
Warning
You don't need
style-loader
anymore, please remove it.
Warning
The
esModules
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
module.exports = { module: { rules: [ { test: /\.(sa|sc|c)ss$/i, use: ["css-loader", "postcss-loader", "sass-loader"], }, ], }, };
src/index.js
import sheet from "./styles.css"; console.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
esModules
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:
- Using CSS Module Scripts to import stylesheets
- Constructable Stylesheets: seamless reusable styles
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: import sheet from "./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
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 and works faster.
Note
Do not use
style-loader
andmini-css-extract-plugin
together.
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const devMode = process.env.NODE_ENV !== "production"; module.exports = { module: { rules: [ { test: /\.(sa|sc|c)ss$/i, use: [ devMode ? "style-loader" : MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "sass-loader", ], }, ], }, plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]), };
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 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 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
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) { return name.replace(/-/g, "_"); }, }, }, }, ], }, };
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 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
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 as
ICSS
-only.
$colorBackground: red; :export { colorBackgroundCanvas: $colorBackground; }
Component.module.scss
File treated as CSS Module
.
@import "variables.scss"; .componentClass { background-color: $colorBackground; }
Component.jsx
Using both
CSS Module
functionality as well as SCSS variables directly in JavaScript.
import svars from "variables.scss"; import styles from "Component.module.scss"; // Render DOM with CSS modules class name //// //// Somewhere in JavaScript canvas drawing code use the variable directly // const ctx = mountsCanvas.current.getContext('2d',{alpha: false}); ctx.fillStyle = `${svars.colorBackgroundCanvas}`;
Contributing
Please take a moment to read our contributing guidelines if you haven't yet done so.
CONTRIBUTING
License
MIT