Как ускорить подключение стилей при использовании Webpack
Недавно я завершил работу над одним своим проектом ( GitHub ), но всё же не устранил одну проблему: стили Bootstrap подключались слишком долго, что приводило к тому, что сперва открывается сайт без стилей, а через секунду всё выглядит нормально. Крайне неприятный момент, который я всё же решил исправить и пошёл искать решение в интернете. В данном посте я расскажу о том, как я подключал стили изначально, и о том, как решил вопрос с CSS.
Как я подключал стили
У меня был файл style.scss , в который я импортировал нужные мне компоненты Bootstrap. Этот файл я импортировал в JavaScript файл, используя Webpack со следующими настройками:
Всё стандартно, подобную настройку вы можете найти в каждом втором туториале по Webpack.
А так выглядит html после сборки:
Получается так, что стили добавляются после обработки js-файла, что плохо, очень плохо
Как я подключил стили
mini-css-extract-plugin — модуль, решивший мою проблему.
Используется он следующим образом:
Что это нам даёт? Теперь Webpack создаёт CSS-файл и подключает его к HTML, который после сборки будет выглядеть так:
Итог
Теперь стили загружаются сразу, что на моем проекте можно увидеть наглядно, посмотрев на кнопку загрузки файлов. У неё есть иконка, которая появляется с помощью JavaScript спустя секунду после загрузки страницы. Тоже неприятно, но уж лучше пусть долго грузится иконка, чем стили всего сайта.
На этом у меня всё, надеюсь данный пост поможет вам сэкономить время, если вы столкнётесь с подобной проблемой.
Как правильно подключить CSS в webpack?
Всем привет.Никак не могу подключить CSS файл к webpack. Пишет ошибку в строке 10 но так как с node.js и npm незнаком очень трудно для меня разобратся. Уже установил style-loader. style.css находится в одном директории с home.js ошибка который я получаю Вот мой webpack.config.js
"use strict"; const webpack = require('webpack'); module.exports = < entry: "./home", output: < filename: "bundle.js" >module: < rules: [ < test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ >, < test: /\.css$/, use: ['style-loader', 'css-loader'] >] > >
Также home.js
import $ from 'jquery'; import css from './style.css';
Отслеживать
задан 1 фев 2018 в 13:58
6,976 4 4 золотых знака 29 29 серебряных знаков 62 62 бронзовых знака
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
Очепятка у вас, после блока output забыли запятую. Забирай:
"use strict"; const webpack = require('webpack'); module.exports = < entry: "./home", output: < filename: "bundle.js" >, module: < rules: [ < test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ >, < test: /\.css$/, use: ['style-loader', 'css-loader'] >] > >
Отслеживать
ответ дан 1 фев 2018 в 14:30
Klimenko Kirill Klimenko Kirill
2,206 1 1 золотой знак 11 11 серебряных знаков 37 37 бронзовых знаков
Спасибо большое и дай бог здоровье 🙂 @Klimenkomud
1 фев 2018 в 14:31
@Избытоксусликов Всегда пожалуйста 🙂
1 фев 2018 в 14:32
- css
- node.js
- webpack
- npm
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.15.1019
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
css-loader
Disclaimer: css-loader is a third-party package maintained by community members, it potentially does not have the same support, security policy or license as webpack, and it is not maintained by webpack.
The css-loader interprets @import and url() like import/require() and will resolve them.
Getting Started
Warning
To use the latest version of css-loader, webpack@5 is required
To begin, you’ll need to install css-loader :
npm install --save-dev css-loader
yarn add -D css-loader
pnpm add -D css-loader
Then add the plugin to your webpack config. For example:
file.js
import css from "file.css";
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, use: ["style-loader", "css-loader"], >, ], >, >;
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.
Options
url
type url = | boolean | filter: (url: string, resourcePath: string) => boolean; >;
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.
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') and require('./image2x.png')
To import assets from a node_modules path (include resolve.modules ) and for alias , 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/disable url() resolving.
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: url: true, >, >, ], >, >;
object
Allow to filter url() . All filtered url() 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` urls if (url.includes("img.png")) return false; > // Don't handle images under root-relative /external_images/ if (/^\/external_images\//.test(path)) return false; > return true; >, >, >, >, ], >, >;
import
type importFn = | boolean | filter: ( url: string, media: string, resourcePath: string, supports?: string, layer?: string ) => boolean; >;
Allows to enables/disables @import at-rules handling. Control @import resolving. Absolute urls in @import will be moved in runtime code.
@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
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: import: true, >, >, ], >, >;
object
filter
type filter = (url: string, media: string, resourcePath: string) => boolean;
Allow to filter @import . All 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` import if (url.includes("style.css")) return false; > return true; >, >, >, >, ], >, >;
modules
type modules = | 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: | "asIs" | "camelCase" | "camelCaseOnly" | "dashes" | "dashesOnly" | ((name: string) => string); exportOnlyLocals: boolean; >;
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 here
- object — 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 here
The 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
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: true, >, >, ], >, >;
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.
:local(.className) background: red; > :local .className color: green; > :local(.className .subClass) color: green; > :local .className .subClass :global(.global-class-name) color: blue; >
._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 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.
:local(.className) background: red; color: yellow; > :local(.subClass) composes: className; background: blue; >
This doesn’t result in any change to the CSS itself but exports multiple classnames.
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 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.
: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"; 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 use prefix v- for values, s- for selectors and m- for media at-rules.
@value v-primary: #BF4040; @value s-black: black-selector; @value m-large: (min-width: 960px); .header color: v-primary; padding: 0 10px; > .s-black color: black; > @media m-large .header padding: 0 20px; > >
boolean
Enable CSS Modules features.
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: true, >, >, ], >, >;
string
Enable CSS Modules features and setup mode .
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
Enable CSS Modules features and setup options for them.
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: "camelCase", exportOnlyLocals: false, >, >, >, ], >, >;
auto
type auto = boolean | regExp | ((resourcePath: string) => boolean);
Allows auto enable CSS modules/ICSS based on filename when modules option is object.
- 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
- 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) condition
- false — disables CSS modules or interoperable CSS format based on filename
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: auto: true, >, >, >, ], >, >;
RegExp
Enable 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
Enable CSS modules for files based on the filename satisfying your filter function check.
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: auto: (resourcePath) => resourcePath.endsWith(".custom-module.css"), >, >, >, ], >, >;
mode
type mode = | "local" | "global" | "pure" | "icss" | ((resourcePath: string) => "local" | "global" | "pure" | "icss");
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
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: mode: "global", >, >, >, ], >, >;
function
Allows set different values for the mode option based on a filename
Possible return values — local , global , pure and icss .
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: // Callback must return "local", "global", or "pure" values mode: (resourcePath) => if (/pure.css$/i.test(resourcePath)) return "pure"; > if (/global.css$/i.test(resourcePath)) return "global"; > return "local"; >, >, >, >, ], >, >;
localIdentName
type localIdentName = string;
Allows to configure the generated local ident name.
For more information on options see:
- webpack template strings,
- output.hashDigest,
- output.hashDigestLength,
- output.hashFunction,
- output.hashSalt.
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
- [:hash::] — hash with hash settings.
- [local] — original class.
- use ‘[path][name]__[local]’ for development
- use ‘[hash:base64]’ for production
The [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
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: localIdentName: "[path][name]__[local]--[hash:base64:5]", >, >, >, ], >, >;
localIdentContext
type localIdentContex = string;
Allows to redefine 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 localIdentHashSalt = string;
Allows to add custom hash to generate more unique classes. For more information see output.hashSalt.
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: localIdentHashSalt: "hash", >, >, >, ], >, >;
localIdentHashFunction
type localIdentHashFunction = string;
Allows to specify hash function to generate classes . For more information see output.hashFunction.
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: localIdentHashFunction: "md4", >, >, >, ], >, >;
localIdentHashDigest
type localIdentHashDigest = string;
Allows to specify hash digest to generate classes. For more information see output.hashDigest.
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: localIdentHashDigest: "base64", >, >, >, ], >, >;
localIdentHashDigestLength
type localIdentHashDigestLength = number;
Allows to specify hash digest length to generate classes. For more information see output.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 localIdentRegExp = string | RegExp;
webpack.config.js
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: localIdentRegExp: /page-(.*)\.css/i, >, >, >, ], >, >;
getLocalIdent
type getLocalIdent = ( context: LoaderContext, localIdentName: string, localName: string ) => string;
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
module.exports = module: rules: [ test: /\.css$/i, loader: "css-loader", options: modules: getLocalIdent: (context, localIdentName, localName, options) => return "whatever_random_class_name"; >, >, >, >, ], >, >;
namedExport
type namedExport = boolean;
Enables/disables ES modules named export for locals.
Warning
Names of locals are converted to camelcase, i.e. the exportLocalsConvention option has camelCaseOnly value by default.
Warning
It is not allowed to use JavaScript reserved words in css class names.
styles.css
.foo-baz color: red; > .bar color: blue; >
index.js
import fooBaz, bar > from "./styles.css"; console.log(fooBaz, bar);
You can enable a 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 use exportLocalsConvention option as a function. Example below in the examples section.
exportGlobals
type exportsGLobals = boolean;
Allow css-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 exportLocalsConvention = | "asIs" | "camelCase" | "camelCaseOnly" | "dashes" | "dashesOnly" | ((name: string) => string);
Default: based on the modules.namedExport option value, if true — camelCaseOnly , otherwise asIs
Style of exported class names.
string
By default, the exported JSON keys mirror the class names (i.e asIs value).
Warning
Only camelCaseOnly value allowed if you set the namedExport value to true .
| 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
.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: "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 exportOnlyLocals = boolean;
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 importLoaders = number;
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 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 esModule = boolean;
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 exportType = "array" | "string" | "css-style-sheet";
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 with CSS 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 with CSS modules , by default for locals will be used named export.
Warning
Source maps are not currently supported in Chrome due bug
Useful for custom elements and shadow DOM.
- 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 and mini-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: [ // 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 ? [] : [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',); ctx.fillStyle = `$`;
Contributing
Please take a moment to read our contributing guidelines if you haven’t yet done so.
Что такое CSS-модули и зачем они нам?
В последнее время меня интригуют CSS-модули. Если вы о них не слышали — эта статья для вас. Мы рассмотрим, что это за проект, какие задачи он решает и каковы причины его возникновения. Если вы тоже заинтриговались — не переключайтесь, следующая статья будет о том, как начать их применять. А если вас интересует внедрение в проект или более продвинутое использование CSS-модулей, третья статья в этой серии будет о том, как использовать их c React.
Серия статей
Часть 1: Что такое CSS-модули и зачем они нам? (Вы её читаете!)
Что такое CSS-модули?
Согласно определению из репозитория, CSS-модули — это:
CSS-файлы, в которых все классы и анимации по умолчанию находятся в локальной области видимости.
CSS-модули — это не официальная спецификация, они не имплементированы в браузеры, скорее, это задача, запускаемая на стадии сборки проекта (например, с помощью Webpack или Browserify), в процессе выполнения которой имена классов и селекторы изменяются так, чтобы образовалась своего рода локальная область видимости (что-то вроде пространства имен).
Как это выглядит и зачем нам это? Сейчас расскажу. Во-первых, вспомните как обычно работают HTML и CSS. Класс прописывается в HTML:
h1 class="title">Пример заголовка h1>
И стилизуется в CSS:
.title < background-color: red; >
Пока CSS применяется к HTML-документу, фон будет красным. Нам не нужно как-то обрабатывать CSS или HTML, оба формата понятны браузеру.
CSS-модули используют другой подход. Вместо того, чтобы писать обычный HTML, нам придётся написать разметку в JavaScript-файле, например, в index.js . Вот как это может выглядеть (ниже мы рассмотрим более реальные примеры):
import styles from "./styles.css"; element.innerHTML = `$ "> Пример заголовка `
;
В процессе сборки компилятор проанализирует styles.css , который мы импортировали, потом проанализирует JavaScript и сделает класс .title доступным через styles.title . Затем сгенерирует на их основе новые HTML и CSS-файлы, уже с новыми классами.
Сгенерированный HTML может выглядеть следующим образом:
h1 class="_styles__title_309571057"> Пример заголовка h1>
А вот так может выглядеть CSS:
._styles__title_309571057 < background-color: red; >

Значение атрибута class и селектор .title заменены на новые. Исходный CSS в браузер вообще не попадает.
Как сказал Хьюго Жироде́ль (Hugo Giraduel) в своей статье по этому поводу:
[классы] генерируются автоматически, они уникальны и привязаны к исходным стилям.
Вот это и называется поместить стили в локальную область видимости. Они находятся в области видимости определенного шаблона. Если у нас есть файл buttons.css , он будет импортирован только в шаблон buttons.js , и класс .btn , который он содержит, будет недоступен для других шаблонов (например, forms.js ), пока мы не импортируем его и туда тоже.
Зачем нам устраивать всю эту канитель с CSS и HTML? Зачем нам это вообще сдалось, ради всего святого?!
Зачем нам нужно использовать CSS-модули?
CSS-модули гарантируют, что все стили одного компонента:
- Находятся в одном месте
- Применяются только к этому компоненту и никакому другому
Кроме того, каждый компонент может иметь настоящие зависимости, например:
import buttons from "./buttons.css"; import padding from "./padding.css"; element.innerHTML = `$ $ ">`;
Этот подход был разработан, что бы решить проблему глобальной области видимости в CSS
Вы когда-нибудь испытывали соблазн в условиях нехватки времени или ресурсов просто писать CSS так быстро, как можете, не думая о последствиях?
Пихали ли в конец таблицы стилей какой-нибудь мусор, собираясь потом его отрефакторить, и так никогда этого и не сделали?
Бывало ли такое, что вы просматривали стили, не до конца понимая что они делают и используются ли они вообще?
Задумывались ли вы, получится ли избавиться от некоторых стилей, ничего при этом не сломав? Не приходилось ли гадать, эти стили работают сами по себе или зависят от других? Случалось ли вам перезаписывать стили?
Это вопросы, которые могут привести к серьезной головной боли, пропущенным дедлайнам и грустным взглядам в окно.
С CSS-модулями и концепцией использования локальной области видимости по умолчанию таких проблем можно избежать. Вам всегда приходится думать о последствиях, когда вы пишите стили.
Например, если вы используете в HTML класс random-gross-class , не обработав его как класс CSS-модуля, стили не применятся, так как CSS-селектор превратится во что-то вроде ._style_random-gross-class_0038089 .
Ключевое слово composes
Допустим, у нас есть модуль под названием type.css , содержащий стили для текста. В этом файле может быть, например, такое:
.serif-font < font-family: Georgia, serif; > .display < composes: serif-font; font-size: 30px; line-height: 35px; >
Один из этих классов мы используем в шаблоне:
import type from "./type.css"; element.innerHTML = `$ "> Пример заголовка `
;
В результате получится такая разметка:
h1 class="_type__display_0980340 _type__serif_404840"> Пример заголовка h1>
Оба класса связаны с элементом через использование ключевого слова composes , решая таким образом некоторые проблемы, которые есть в похожих решениях, например в @extend Sass.
Так можно даже подставлять данные из отдельного CSS-файла:
.element < composes: dark-red from "./colors.css"; font-size: 30px; line-height: 1.2; >
БЭМ не нужен
Нам не нужен БЭМ, если мы используем CSS-модули. По двум причинам:
- Простота чтения. Код вроде type.display так же понятен для разработчика, как и .font-size__serif—large из БЭМ. Его даже проще читать, чем разросшиеся БЭМ-селекторы.
- Локальная область видимости. Допустим, в одном из модулей у нас есть класс .big и он увеличивает font-size на некоторую величину. В другом модуле у нас есть точно такой же класс .big , который увеличивает padding и font-size на другую величину. И это не имеет никакого значения! Они не будут конфликтовать, так как у стилей различаются области видимости. Даже если модуль импортирует обе таблицы стилей, у классов будет своё уникальное имя, созданное в процессе сборки специально для них. Другими словами, при использовании CSS-модулей проблемы специфичности селекторов просто исчезают.
И это только некоторые из достоинств использования CSS-модулей.
Если вам интересно узнать больше, Глен Маден (Glen Madden) много пишет на эту тему.
В следующей статье из этой серии мы рассмотрим как поднять проект используя Webpack и CSS-модули. Мы будем использовать для этого новейшие возможности ES2015 и рассмотрим в процессе несколько примеров, чтобы в полной мере разобраться в происходящем.
Материалы для дальнейшего изучения
- CSS-модули: Добро пожаловать в будущее
- Руководство по CSS-модулям Хьюго Жирауделя (Hugo Giraudel) на Sitepoint
- Разбираемся с модулями в ES6
- Учим ES2015
- Знакомимся с синтаксисом модулей ES6
