Webpack css-loader

css-loader​ 会对 ​@import 和 url()​ 进行处理,就像 js 解析 ​import/require()​ 一样。

快速开始

如果要使用 css-loader,你需要安装 webpack@5

首先,你需要先安装 ​css-loader​:

npm install --save-dev css-loader

然后把 loader 引用到你 webpack 的配置中。如下所示:

file.js

import css from "file.css";

webpack.config.js

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

然后运行 webpack。

如果由于某种原因你需要将 CSS 提取为一个文件(即不要将 CSS 存储在 JS 模块中),你可能想要查看 推荐示例

配置项

名称类型默认值描述
url

{Boolean|Function}

true

启用/禁用 url()/image-set() 函数处理
import

{Boolean|Function}

true

启用/禁用 @import 规则进行处理
modules

{Boolean|String|Object}

{auto: true}

启用/禁用 CSS 模块及其配置
sourceMap

{Boolean}

compiler.devtool

启用/禁用生成 SourceMap
importLoaders

{Number}

0

启用/禁用或者设置在 css-loader 前应用的 loader 数量
esModule

{Boolean}

true

使用 ES 模块语法
exportType

{array | string | css-style-sheet}

array

允许导出样式为模块数组、字符串或者 可构造样式(即 CSSStyleSheet

url

类型: Boolean|Object 默认值: true

启用/禁用 url/image-set 函数进行处理。 如果设置为 false,css-loader 将不会解析 url 或者 image-set 中的任何路径。 还可以传递给一个函数基于资源的路径动态地控制这种行为。 绝对路径和根目录的相对 URL 现在会被解析(版本 4.0.0。

示例解决方案:

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)

要从 node_modules 目录(包括 resolve.modules)导入资源,而对于 alias,请加上一个前缀 ~:

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

启用/禁用 url() 解析。

webpack.config.js

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

Object

允许过滤 url()。所有过滤的内容 url() 都不会解析(保留编写时的代码)。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /.css$/i,
        loader: "css-loader",
        options: {
          url: {
            filter: (url, resourcePath) => {
              // resourcePath - css 文件的路径

              // 不处理 `img.png` url
              if (url.includes("img.png")) {
                return false;
              }

              return true;
            },
          },
        },
      },
    ],
  },
};

import

类型: Boolean|Object 默认值: true

启用/禁用 @import 规则进行处理。 控制 @import 的解析。@import 中的绝对 URL 会被直接移到运行时去处理。

示例解决方案:

@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

要从 node_modules 目录(包括 resolve.modules)导入样式,而对于 alias,请加上一个前缀 ~:

@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

启用/禁用 @import 解析。

webpack.config.js

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

Object

名称类型默认值描述
filter

{Function}

undefined

允许过滤 @import

filter

类型:Function 默认值:undefined

允许过滤 @import。所有过滤的内容 @import 都不会解析(保留编写时的代码)。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /.css$/i,
        loader: "css-loader",
        options: {
          import: {
            filter: (url, media, resourcePath) => {
              // resourcePath - css 文件路径

              // 不处理 `style.css` 的导入
              if (url.includes("style.css")) {
                return false;
              }

              return true;
            },
          },
        },
      },
    ],
  },
};

modules

类型:Boolean|String|Object 默认值:undefined

启用/禁用 CSS 模块或者 ICSS 及其配置:

  • undefined – 为所有匹配 /.module.w+$/i.test(filename) 与 /.icss.w+$/i.test(filename) 正则表达式的文件启用 CSS 模块。
  • true – 对所有文件启用 CSS 模块。
  • false – 对所有文件禁用 CSS 模块。
  • string – 对所有文件禁用 CSS 模块并设置 mode 配置项,你可以在 这里 获得更多信息。
  • object – 如果没有配置 modules.auto 则对所有文件启用 CSS 模块,否则 modules.auto 配置项则会决定其是否为 CSS 模块,你可以在 这里 获得更多信息。

该 modules 选项启用/禁用 CSS 模块 规范并且设置基本的行为。

设置为 false 值会提升性能,因为避免了 CSS Modules 特性的解析,这对于使用普通 CSS 或者其他技术的开发人员是非常有用的。

webpack.config.js

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

Features

Scope

使用 local 值要求你指定 :global 类。 使用 global 值要求你指定 :local 类。 使用 pure 值则要求必须至少包含一个局部类或者 id。

你可以点击 此处 了解更多。

样式可以在局部作用域中,避免影响全局作用域的样式。

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

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

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

: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;
}

ℹ️ 被导出的标识符

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

本地选择器推荐使用驼峰命名。它们在导入的 JS 模块中更容易使用。

你也可以使用 :local(#someId),但这并不推荐。应该使用类去代替 id。

Composing

声明本地类名时,可以从另一个本地类名组成一个本地类。

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

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

这不会导致 CSS 本身发生任何变化,但是会导出多个类名。

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

._13LGdX8RMStbBE9w-t0gZ1 {
  background: blue;
}
Importing

从另一个模块导入本地类名。

我强烈建议您在导入文件时指定扩展名,因为可以导入具有任何扩展名的文件,而且事先并不能知道要使用哪个文件。

:local(.continueButton) {
  composes: button from "library/button.css";
  background: red;
}
:local(.nameEdit) {
  composes: edit highlight from "./edit.css";
  background: red;
}

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

:local(.className) {
  composes: edit hightlight from "./edit.css";
  composes: button from "module/button.css";
  composes: classFromThisModule;
  background: red;
}
Values

可以使用 @value 来指定在整个文档中都能被重复使用的值,

我们推荐对特定的值使用 v- 的前缀,给选择器使用 s- 的前缀,并且为媒体规则使用 m- 前缀。

@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

启用 CSS 模块 功能。

webpack.config.js

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

String

启用 CSS 模块 功能和设置 mode。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /.css$/i,
        loader: "css-loader",
        options: {
          // 使用 `local` 同使用 `modules: true` 的效果是一样的
          modules: "global",
        },
      },
    ],
  },
};

Object

启用 CSS 模块 功能和设置选项。

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

类型:Boolean|RegExp|Function 默认值:undefined

当 modules 配置项为对象时允许基于文件名自动启用 CSS 模块或者 ICSS。

有效值:

  • undefined – 为所有文件启用 CSS 模块。
  • true – 为所有匹配 /.module.w+$/i.test(filename) 和 /.icss.w+$/i.test(filename) 正则表达式的文件启用 CSS 模块。
  • false – 禁用 CSS 模块。
  • RegExp – 为所有匹配 /RegExp/i.test(filename) 正则表达式的文件禁用 CSS 模块。
  • function – 为所有通过基于文件名的过滤函数校验的文件启用 CSS 模块。
Boolean

可能的值:

  • true – 启用 CSS 模块或者可交互 CSS 格式,为所有满足 /.module(s)?.w+$/i.test(filename) 条件的文件设置 modules.mode 选项为 local,或者为所有满足 /.icss.w+$/i.test(filename) 条件的文件设置  modules.mode 选项为 icss
  • false – 禁用 css 模块或者基于文件名的可交互 CSS 格式

webpack.config.js

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

根据正则表达式检查文件名,为匹配的文件启用 css 模块。

webpack.config.js

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

根据过滤器检查文件名,为满足过滤要求的文件启用css模块。

webpack.config.js

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

类型:String|Function 默认:​local

设置 mode 选项。需要 local 模式时可以忽略该值。

控制应用于输入样式的编译级别。

local、global 和 pure 处理 class 和 id 域以及 @value 值。 icss 只会编译底层的 Interoperable CSS 格式,用于声明 CSS 和其他语言之间的 :import 和 :export 依赖关系。

ICSS 提供 CSS Module 支持,并且为其他工具提供了一个底层语法,以实现它们自己的 css-module 变体。

String

可选值 – local、global、pure 和 icss。

webpack.config.js

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

允许根据文件名设置不同的 mode 选项值。

可能的返回值 – local、global、pure 和 icss。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            // 回调必须返回 `local`,`global`,或者 `pure`
            mode: (resourcePath) => {
              if (/pure.css$/i.test(resourcePath)) {
                return "pure";
              }

              if (/global.css$/i.test(resourcePath)) {
                return "global";
              }

              return "local";
            },
          },
        },
      },
    ],
  },
};
localIdentName

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

允许配置生成的本地标识符(ident)。

更多关于配置项的信息可以查看:

  • webpack template strings​,
  • output.hashDigest​,
  • output.hashDigestLength​,
  • output.hashFunction​,
  • output.hashSalt.

支持的模板字符串:

  • [name]​ 源文件名称
  • [folder]​ 文件夹相对于 compiler.context 或者 modules.localIdentContext 配置项的相对路径。
  • [path]​ 源文件相对于 compiler.context 或者 modules.localIdentContext 配置项的相对路径。
  • [file]​ – 文件名和路径。
  • [ext]​ – 文件拓展名。
  • [hash]​ – 字符串的哈希值。基于 localIdentHashSalt、localIdentHashFunction、localIdentHashDigest、localIdentHashDigestLength、localIdentContext、resourcePath 和 exportName 生成。
  • [<hashFunction>:hash:<hashDigest>:<hashDigestLength>]​ – 带有哈希设置的哈希。
  • [local]​ – 原始类名。

建议:

  • 开发环境使用 [path][name]__[local]
  • 生产环境使用 [hash:base64]

[local] 占位符包含原始的类。

**注意:**所有保留 (<>:”/|?*) 和控制文件系统字符 (不包括 [local] 占位符) 都将转换为 -。

webpack.config.js

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

类型:String 默认:compiler.context

允许为本地标识符名称重新定义基本的 loader 上下文。

webpack.config.js

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

类型:String 默认:undefined

允许添加自定义哈希值以生成更多唯一类。 更多信息请查看 output.hashSalt。

webpack.config.js

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

类型:String 默认值:md4

允许设置生成 class 的哈希函数。 更多信息请查看 output.hashFunction。

webpack.config.js

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

类型:String 默认值:hex

允许设置生成 class 的哈希摘要。 更多信息请查看 output.hashDigest。

webpack.config.js

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

类型:Number 默认值:20

允许设置生成 class 的哈希摘要长度。 更多信息请查看 output.hashDigestLength。

webpack.config.js

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

类型:String|RegExp 默认:undefined

webpack.config.js

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

类型:Function 默认:undefined

可以指定自定义 getLocalIdent 函数的绝对路径,以基于不同的架构生成类名。 默认情况下,我们使用内置函数来生成 classname。 如果自定义函数返回 null 或者 undefined, 我们将降级使用内置函数来生成 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

类型:Boolean 默认:false

本地环境启用/禁用 export 的 ES 模块。

⚠ 本地环境的命名将转换为驼峰格式,即 exportLocalsConvention 选项默认设置了 camelCaseOnly。

⚠ 不允许在 CSS 类名中使用 JavaScript 保留字。

styles.css

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

index.js

import { fooBaz, bar } from "./styles.css";

console.log(fooBaz, bar);

可以使用以下命令启用 export 的 ES 模块:

webpack.config.js

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

可以为 namedExport 设置一个自定义名称,可以使用 exportLocalsConvention 配置项作为一个函数。 可前往 examples 章节查看示例。

exportGlobals

类型:Boolean 默认:false

允许 css-loader 从全局类或 ID 导出名称,因此您可以将其用作本地名称。

webpack.config.js

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

类型:String|Function 默认:取决于 modules.namedExport 选项值,如果为 true 则对应的是 camelCaseOnly,反之对应的是 asIs

导出的类名称的样式。

String

默认情况下,导出的 JSON 密钥反映了类名(即 asIs 值)。

⚠ 如果你设置 namedExport 为 true 那么只有 camelCaseOnly 被允许。

名称类型描述
asIs

{String}

类名将按原样导出。
camelCase

{String}

类名将被驼峰化,原类名不会从局部环境删除
camelCaseOnly

{String}

类名将被驼峰化,原类名从局部环境删除
dashes

{String}

类名中只有破折号会被驼峰化
dashesOnly

{String}

类名中破折号会被驼峰,原类名从局部环境删除

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

类型:Boolean 默认:false

仅导出局部环境。

使用 css 模块 进行预渲染(例如 SSR)时很有用。 要进行预渲染,预渲染包 应使用 mini-css-extract-plugin 选项而不是 style-loader!css-loader。 它不嵌入 CSS,而仅导出标识符映射。

webpack.config.js

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

importLoaders

类型:Number 默认:0

允许为 @import 样式规则、CSS 模块或者 ICSS 启用/禁用或设置在 CSS loader 之前应用的 loader 的数量,例如:@import/composes/@value value from ./values.css 等。

importLoaders 选项允许你配置在 css-loader 之前有多少 loader 应用于 @imported 资源与 CSS 模块/ICSS 导入。

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

当模块系统(即 webpack)支持按来源匹配 loader 时,这种情况将来可能会改变。

sourceMap

类型:Boolean 默认值:取决于 compiler.devtool 值

source map 的生成默认依赖 devtool 配置项。除了 eval 与 false 之外的值都会启用 source map。

webpack.config.js

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

esModule

类型:Boolean 默认:true

默认情况下,css-loader 生成使用 ES 模块语法的 JS 模块。 在某些情况下,使用 ES 模块是有益的,例如在模块串联或 tree shaking 时。

你可以使用以下方式启用 CommonJS 模块语法:

webpack.config.js

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

exportType

类型:array | string | css-style-sheet 默认值:array

允许导出样式为模块数组、字符串或者 可构造样式(即 CSSStyleSheet)。 默认值为 array,即 loader 导出具有特定 API 的模块数组,用于 style-loader 或其他。

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

loader 导出具有特定 API 的模块数组,用于 style-loader 或其他。

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

⚠ 你不再需要 style-loader,请移除它。 ⚠ 如果你想使用 CSS modules,应该启用 esModules 配置项,默认情况下,本地变量会被 具名导出。

默认导出为 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

⚠ 不再允许使用 @import 规则,更多 信息 ⚠ 你不再需要 style-loader,请移除它。 ⚠ 如果你想使用 CSS modules,应该启用 esModules 配置项,默认情况下,本地变量会被 具名导出。 ⚠ 目前在 Chrome 中不支持 Source maps,因为有该 bug

默认导出是一个 可构造样式 (即 CSSStyleSheet)。

对 自定义元素 以及 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];

对于迁移,你可以使用以下配置:

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

示例

推荐

推荐 production 环境的构建将 CSS 从你的 bundle 中分离出来,这样可以使用 CSS/JS 文件的并行加载。 这可以通过使用 mini-css-extract-plugin 来实现,因为它可以创建单独的 CSS 文件。 对于 development 模式(包括 webpack-dev-server),你可以使用 style-loader,因为它可以使用多个 标签将 CSS 插入到 DOM
中,并且反应会更快。

i 不要同时使用 style-loader 与 mini-css-extract-plugin。

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

使用 /* webpackIgnore: true */ 注释禁用 url 解析

有了 /* webpackIgnore: true */ 注释,可以禁用对规则和单个声明的源处理。

/* webpackIgnore: true */
@import url(./basic.css);
@import /* webpackIgnore: true */ url(./imported.css);

.class {
  /* 对 background 声明中的所有 url 禁用 url 处理 */
  color: red;
  /* webpackIgnore: true */
  background: url("./url/img.png"), url("./url/img.png");
}

.class {
  /* 对 background 声明中第一个 url 禁用 url 处理 */
  color: red;
  background:
    /* webpackIgnore: true */ url("./url/img.png"), url("./url/img.png");
}

.class {
  /* 对 background 声明中第二个 url 禁用 url 处理 */
  color: red;
  background: url("./url/img.png"),
    /* webpackIgnore: true */ url("./url/img.png");
}

/* prettier-ignore */
.class {
  /* 对 background 声明中第二个 url 禁用 url 处理 */
  color: red;
  background: url("./url/img.png"),
    /* webpackIgnore: true */
    url("./url/img.png");
}

/* prettier-ignore */
.class {
  /* 对 background-image 声明中第三和第六个 url 禁用 url 处理 */
  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

如下配置的 webpack.config.js 可以加载 CSS 文件,嵌入小的 PNG/JPG/GIF/SVG 图片以及字体作为数据 URL,并将较大的文件复制到输出目录。

对于 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,
        // 更多信息请点击这里 https://webpack.js.org/guides/asset-modules/
        type: "asset",
      },
    ],
  },
};

Extract

在生产构建中,建议将CSS从捆绑包中提取出来,以便稍后可以并行加载CSS/JS资源。

在生产模式下,可以使用mini-css-extract-plugin插件来提取CSS。作为替代方案,如果希望获得更好的开发性能和模拟生产环境的CSS输出,可以使用extract-css-chunks-webpack-plugin,它提供了一个与mini-css-extract-plugin相似但适用于热模块重新加载的扩展版本。

在开发环境中,可以实时加载真实的CSS文件,而在非开发环境中则与mini-css类似。

    纯 CSS,CSS 模块和 PostCSS

    如果项目中没有纯 CSS(没有 CSS 模块),CSS 模块和 PostCSS,则可以使用以下设置:

    webpack.config.js

    module.exports = {
      module: {
        rules: [
          {
            // 对于 pure CSS - /.css$/i,
            // 对于 Sass/SCSS - /.((c|sa|sc)ss)$/i,
            // 对于 Less - /.((c|le)ss)$/i,
            test: /.((c|sa|sc)ss)$/i,
            use: [
              "style-loader",
              {
                loader: "css-loader",
                options: {
                  // 每一个 CSS 的 `@import` 与 CSS 模块/ICSS 都会运行 `postcss-loader`,不要忘了 `sass-loader` 将不属于 CSS 的 `@import` 编译到一个文件中
                  // 如果您需要在每个 CSS 的 `@import` 上运行 `sass-loader` 和 `postcss-loader`,请将其设置为 `2`。
                  importLoaders: 1,
                },
              },
              {
                loader: "postcss-loader",
                options: { plugins: () => [postcssPresetEnv({ stage: 0 })] },
              },
              // 也可能是 `less-loader`
              {
                loader: "sass-loader",
              },
            ],
          },
          // 对于 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",
          },
        ],
      },
    };

    使用别名解析未解析的 URL

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

    只允许 可交互的 CSS 使其与 CSS Module 特性分离

    下面是有关配置的示例代码,通过为所有未匹配到 *.module.scss 命名约定文件设置 mode 选项,只允许使用 可交互的 CSS 特性(如 :import 和 :export),而不使用其他的 CSS Module 特性。此处仅供参考,因为在 v4 之前,css-loader 默认将 ICSS 特性应用于所有文件。 同时,在本示例中,匹配到 *.module.scss 的所有文件都将被视为 CSS
    Modules。

    假设项目中有这样一个需求,要求 canvas 绘制使用的变量与 CSS 同步,换句话说就是 canvas 绘制使用的颜色(在 JavaScript 中设置的颜色名)与 HTML 背景(在 CSS 中通过 class 设置)相同。

    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

    文件被视为仅使用 ICSS。

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

    Component.module.scss

    文件被视为 CSS Module。

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

    Component.jsx

    在 JavaScript 中直接使用 CSS Module 的特性以及 SCSS 声明的变量。

    import svars from "variables.scss";
    import styles from "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

    如果您还没有阅读,请花一点时间阅读我们的贡献指南。

    License

    MIT

    作者:冒牌SEO,如若转载,请注明出处:https://www.web176.com/webpack/22652.html

    (0)
    打赏 支付宝 支付宝 微信 微信
    冒牌SEO冒牌SEO
    上一篇 2023年5月26日
    下一篇 2023年5月26日

    相关推荐

    发表回复

    您的电子邮箱地址不会被公开。 必填项已用*标注