css-loader

[![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![coverage][cover]][cover-url] [![chat][chat]][chat-url] [![size][size]][size-url]

The css-loader interprets @import and url() like import/require() and will resolve them.

起步

To begin, you’ll need to install css-loader:

  1. npm install --save-dev css-loader

Then add the plugin to your webpack config. For example:

file.js

  1. import css from 'file.css';

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. use: ['style-loader', 'css-loader'],
  7. },
  8. ],
  9. },
  10. };

对于这些引用资源,你应该在配置中指定的,比较合适的 loader 是 file-loaderurl-loader(查看如下设置)。

And run webpack via your preferred method.

toString

你也可以直接将 css-loader 的结果作为字符串使用,例如 Angular 的组件样式。

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. use: ['to-string-loader', 'css-loader'],
  7. },
  8. ],
  9. },
  10. };

或者

  1. const css = require('./test.css').toString();
  2. console.log(css); // {String}

如果有 SourceMap,它们也将包含在字符串结果中。

如果由于某种原因,你需要将 CSS 提取为纯粹的字符串资源 (即不包含在 JS 模块中), 则可能需要查看 extract-loader。 例如,当你需要将 CSS 作为字符串进行后处理时,这很有用。

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. use: [
  7. 'handlebars-loader', // handlebars loader expects raw resource string
  8. 'extract-loader',
  9. 'css-loader',
  10. ],
  11. },
  12. ],
  13. },
  14. };

选项

名称

类型

默认值

描述

名称

url

类型

{Boolean|Function}

默认值

true

描述

启用/禁用 url() 处理

名称

import

类型

{Boolean\/Function}

默认值

true

描述

启用/禁用 @import 处理

名称

modules

类型

{Boolean\/Function}

默认值

false

描述

启用/禁用 CSS 模块和设置模式

名称

localIdentName

类型

{String}

默认值

[hash:base64]

描述

配置生成资源的标识符名称

名称

context

类型

{String}

默认值

undefined

描述

Allow to redefine basic loader context for local ident name

名称

hashPrefix

类型

{String}

默认值

undefined

描述

Allow to add custom hash to generate more unique classes

名称

getLocalIdent

类型

{Function}

默认值

undefined

描述

Configure the function to generate classname based on a different schema

名称

sourceMap

类型

{Boolean}

默认值

false

描述

启用/禁用 sourcemap

名称

camelCase

类型

{Boolean|String}

默认值

false

描述

以驼峰式命名导出类名

名称

importLoaders

类型

{Number}

默认值

0

描述

在 css-loader 前应用的 loader 的数量

名称

exportOnlyLocals

类型

{Boolean}

默认值

false

描述

Export only locals

url

类型:Boolean|Function 默认:true

Control url() resolving. Absolute URLs and root-relative URLs are not resolving.

Examples resolutions:

  1. url(image.png) => require('./image.png')
  2. url('image.png') => require('./image.png')
  3. url(./image.png) => require('./image.png')
  4. url('./image.png') => require('./image.png')
  5. url('http://dontwritehorriblecode.com/2112.png') => require('http://dontwritehorriblecode.com/2112.png')
  6. 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 ~:

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

Boolean

Enable/disable url() resolving.

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. url: true,
  9. },
  10. },
  11. ],
  12. },
  13. };

Function

Allow to filter url(). All filtered url() will not be resolved (left in the code as they were written).

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. url: (url, resourcePath) => {
  9. // resourcePath - path to css file
  10. // `url()` with `img.png` stay untouched
  11. return url.includes('img.png');
  12. },
  13. },
  14. },
  15. ],
  16. },
  17. };

import

类型:Boolean 默认:true

Control @import resolving. Absolute urls in @import will be moved in runtime code.

Examples resolutions:

  1. @import 'style.css' => require('./style.css')
  2. @import url(style.css) => require('./style.css')
  3. @import url('style.css') => require('./style.css')
  4. @import './style.css' => require('./style.css')
  5. @import url(./style.css) => require('./style.css')
  6. @import url('./style.css') => require('./style.css')
  7. @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 ~:

  1. @import url(~module/style.css) => require('module/style.css')
  2. @import url('~module/style.css') => require('module/style.css')
  3. @import url(~aliasDirectory/style.css) => require('otherDirectory/style.css')

Boolean

Enable/disable @import resolving.

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. import: true,
  9. },
  10. },
  11. ],
  12. },
  13. };

Function

Allow to filter @import. All filtered @import will not be resolved (left in the code as they were written).

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. import: (parsedImport, resourcePath) => {
  9. // parsedImport.url - url of `@import`
  10. // parsedImport.media - media query of `@import`
  11. // resourcePath - path to css file
  12. // `@import` with `style.css` stay untouched
  13. return parsedImport.url.includes('style.css');
  14. },
  15. },
  16. },
  17. ],
  18. },
  19. };

modules modules“ class=”icon-link” href=”#modules”>

类型:Boolean|String 默认:false

The modules option enables/disables the CSS Modules spec and setup basic behaviour.

Name

Type

Description

Name

true

Type

{Boolean}

Description

Enables local scoped CSS by default (use local mode by default)

Name

false

Type

{Boolean}

Description

Disable the CSS Modules spec, all CSS Modules features (like @value, :local, :global and composes) will not work

Name

'local'

Type

{String}

Description

Enables local scoped CSS by default (same as true value)

Name

'global'

Type

{String}

Description

Enables global scoped CSS by default

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.

You can read about modes below.

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. modules: true,
  9. },
  10. },
  11. ],
  12. },
  13. };
Scope

Using local value requires you to specify :global classes. Using global value requires you to specify :local classes.

You can find more information here.

Styles can be locally scoped to avoid globally scoping styles.

语法 :local(.className) 可以被用来在局部作用域中声明 className。局部的作用域标识符会以模块形式暴露出去。

使用 :local(无括号)可以为此选择器启用局部模式。 :global(.className) 可以用来声明一个明确的全局选择器。 使用 :global(无括号)可以将此选择器切换至全局模式。

loader 会用唯一的标识符(identifier)来替换局部选择器。所选择的唯一标识符以模块形式暴露出去。

  1. :local(.className) {
  2. background: red;
  3. }
  4. :local .className {
  5. color: green;
  6. }
  7. :local(.className .subClass) {
  8. color: green;
  9. }
  10. :local .className .subClass :global(.global-class-name) {
  11. color: blue;
  12. }
  1. ._23_aKvs-b8bW2Vg3fwHozO {
  2. background: red;
  3. }
  4. ._23_aKvs-b8bW2Vg3fwHozO {
  5. color: green;
  6. }
  7. ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 {
  8. color: green;
  9. }
  10. ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name {
  11. color: blue;
  12. }

ℹ️ 主要信息: 标识符被导出

  1. exports.locals = {
  2. className: '_23_aKvs-b8bW2Vg3fwHozO',
  3. subClass: '_13LGdX8RMStbBE9w-t0gZ1',
  4. };

建议局部选择器使用驼峰式。它们在导入 JS 模块中更容易使用。

你可以使用 :local(#someId),但不推荐这种用法。推荐使用 class 代替 id。

Composing

当声明一个局部类名时,你可以与另一个局部类名组合为一个局部类。

  1. :local(.className) {
  2. background: red;
  3. color: yellow;
  4. }
  5. :local(.subClass) {
  6. composes: className;
  7. background: blue;
  8. }

这不会导致 CSS 本身的任何更改,而是导出多个类名。

  1. exports.locals = {
  2. className: '_23_aKvs-b8bW2Vg3fwHozO',
  3. subClass: '_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO',
  4. };
  1. ._23_aKvs-b8bW2Vg3fwHozO {
  2. background: red;
  3. color: yellow;
  4. }
  5. ._13LGdX8RMStbBE9w-t0gZ1 {
  6. background: blue;
  7. }
Importing

从其他模块导入局部类名。

  1. :local(.continueButton) {
  2. composes: button from 'library/button.css';
  3. background: red;
  4. }
  1. :local(.nameEdit) {
  2. composes: edit highlight from './edit.css';
  3. background: red;
  4. }

要从多个模块导入,请使用多个 composes: 规则。

  1. :local(.className) {
  2. composes: edit hightlight from './edit.css';
  3. composes: button from 'module/button.css';
  4. composes: classFromThisModule;
  5. background: red;
  6. }

localIdentName

类型:String 默认:[hash:base64]

You can configure the generated ident with the localIdentName query parameter. See loader-utils’s documentation for more information on options.

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. modules: true,
  9. localIdentName: '[path][name]__[local]--[hash:base64:5]',
  10. },
  11. },
  12. ],
  13. },
  14. };

context

类型:String 默认:undefined

Allow to redefine basic loader context for local ident name. By default we use rootContext of loader.

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. modules: true,
  9. context: path.resolve(__dirname, 'context'),
  10. },
  11. },
  12. ],
  13. },
  14. };

hashPrefix

类型:String 默认:undefined

Allow to add custom hash to generate more unique classes.

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. modules: true,
  9. hashPrefix: 'hash',
  10. },
  11. },
  12. ],
  13. },
  14. };

getLocalIdent

类型:Function 默认:undefined

You can also specify the absolute path to your custom getLocalIdent function to generate classname based on a different schema. By default we use built-in function to generate a classname.

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. modules: true,
  9. getLocalIdent: (context, localIdentName, localName, options) => {
  10. return 'whatever_random_class_name';
  11. },
  12. },
  13. },
  14. ],
  15. },
  16. };

sourceMap

类型:Boolean 默认:false

设置 sourceMap 选项查询参数来引入 source map。

例如,mini-css-extract-plugin 能够处理它们。

默认情况下不启用它们,因为它们会导致运行时的额外开销,并增加了 bundle 大小 (JS source map 不会)。此外,相对路径是错误的,你需要使用包含服务器 URL 的绝对公用路径。

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. sourceMap: true,
  9. },
  10. },
  11. ],
  12. },
  13. };

camelCase

类型:Boolean|String 默认:false

默认情况下,导出 JSON 键值对形式的类名。如果想要驼峰化(camelize)类名(有助于在 JS 中使用),通过设置 css-loader 的查询参数 camelCase 即可实现。

名称

类型

描述

名称

false

类型

{Boolean}

描述

Class names will be camelized, the original class name will not to be removed from the locals

名称

true

类型

{Boolean}

描述

类名将被骆驼化

名称

'dashes'

类型

{String}

描述

只有类名中的破折号将被骆驼化

名称

'only'

类型

{String}

描述

0.27.1 中加入。类名将被骆驼化,初始类名将从局部移除

名称

'dashesOnly'

类型

{String}

描述

0.27.1 中加入。类名中的破折号将被骆驼化,初始类名将从局部移除

file.css

  1. .class-name {
  2. }

file.js

  1. import { className } from 'file.css';

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. camelCase: true,
  9. },
  10. },
  11. ],
  12. },
  13. };

importLoaders

类型:Number 默认:0

查询参数 importLoaders,用于配置「css-loader 作用于 @import 的资源之前」有多少个 loader。

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. use: [
  7. 'style-loader',
  8. {
  9. loader: 'css-loader',
  10. options: {
  11. importLoaders: 2, // 0 => no loaders (default); 1 => postcss-loader; 2 => postcss-loader, sass-loader
  12. },
  13. },
  14. 'postcss-loader',
  15. 'sass-loader',
  16. ],
  17. },
  18. ],
  19. },
  20. };

在模块系统(即 webpack)支持原始 loader 匹配后,此功能可能在将来会发生变化。

exportOnlyLocals

类型:Boolean 默认:false

Export only locals (useful when you use css modules). 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

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. loader: 'css-loader',
  7. options: {
  8. exportOnlyLocals: true,
  9. },
  10. },
  11. ],
  12. },
  13. };

示例

资源

以下 webpack.config.js 可以加载 CSS 文件,将小体积 PNG/JPG/GIF/SVG 图像转为像字体那样的 Data URL 嵌入,并复制较大的文件到输出目录。

webpack.config.js

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.css$/,
  6. use: ['style-loader', 'css-loader'],
  7. },
  8. {
  9. test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
  10. loader: 'url-loader',
  11. options: {
  12. limit: 10000,
  13. },
  14. },
  15. ],
  16. },
  17. };

提取

对于生产环境构建,建议从 bundle 中提取 CSS,以便之后可以并行加载 CSS/JS 资源。

  • 可以通过使用 mini-css-extract-plugin 来实现,在生产环境模式运行中提取 CSS。

  • 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

贡献

Please take a moment to read our contributing guidelines if you haven’t yet done so.

贡献指南

License

MIT