@Dale-Lin
2022-03-19T06:59:29.000000Z
字数 2215
阅读 779
webpack5
css-loader 用于处理 css 文件中的 url()、@import 等语法在打包后的路径。
options.modules 可以用一个对象来配置规则:
{auto: true (对 `/\.module\.\w+$/i.test(filename) 启用 CSS modules)| undefined(对全部文件启用,默认)| false(对全部文件关闭)| RegExp(对匹配的文件名启用),mode: 'local'(只对本地的 class/id 编译,默认)| 'global'(对全局的 class/id 编译,即 CSS 声明作用域变成全局的了)localIdentName: '[hash:base64]'(默认)支持的 webpack template strings:- [name]: 文件名,不包括扩展名- [folder]: 资源相对于 localIdentContext 或 compiler.context 的文件夹- [path]: 资源相对于 localIdentContext 或 compiler.context 的路径,不包括文件名- [file]: [path] + [name]- [ext]: 扩展名,前面带 . 符号- [hash]: hash string,基于 localIdentHashSalt, localIdentHashFunction, localIdentHashDigest, localIdentHashDigestLength,localIdentContext, resourcePath, exportName 生成- [<hashFunction>:hash:<hashDigest>:<hashDigestLength>]: 自定义 hash 设置- [local]: 原始的 class推荐设置:- [path][name]__[local] 开发模式- [hash:base64] 生产模式localIdentContext: 自定义 loader 处理 localIdentName 的上下文目录,默认等于 compiler.context,例如设成 path.resolve(__dirname, "src")nameExport: boolean(支持单独导出 CSS name,class 会转成驼峰导出,默认 false)importLoaders: number设置 css-loader 处理 `@import` 的 CSS 资源前,需要先应用的 loader 有几个。例如用了 less + postcss,那就需要先应用 2 个。}
localIdentName 中
[path][name]会把/.等符号转成-来拼接。
生产环境推荐用 mini-css-extract-plugin 抽出 CSS,可以在浏览器请求资源时并行下载;开发环境使用 style-loader 生成 标签注入 DOM 效率更高。
不要同时使用 style-loader 和 mini-css-extract-plugin 。
// webpack.config.jsconst MiniCssExtractPlugin = require("mini-css-extract-plugin")const devMode = process.env.NODE_ENV !== "production"module.exports = {module: {rules: [{test: /\.(le|c)ss$/i,use: [devMode ? "style-loader" : MiniCssExtractPlugin.loader,"css-loader","postcss-loader","less-loader"],exclude: /node_modules/}]},plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()])}
嵌入的小图片(PNG/JPG/GIF/SVG/字体文件)可以被处理成 Data URLs,大文件可以被复制到 output 目录:
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"}]}}
使用 less 和 postcss:
module.exports = {module: {rules: [{test: /\.(le|c)ss$/i,use: ["style-loader",{loader: "css-loader",options: {importLoaders: 2}},{loader: "postcss-loader",options: {plugins: () => [postcssPresetEnv({ stage: 0 })]}},"less-loader"]},{test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,// https://webpack.js.org/guides/asset-modules/type: "asset"}]}}