webpack - 如何使用 Webpack 5 选择性地在 CSS 中内联 SVG?
问题描述
我正在使用 Webpack 5 将我的 SCSS 编译为 CSS。我想有选择地内联一些 SVG。理想情况下,我想通过文件名、路径或 URL 中的某些查询参数来实现这一点。
假设我有以下 SCSS:
/* src/scss/main.scss */
.logo {
background-image: url('/images/logo.svg');
}
这webpack.config.js
:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const src_dir = path.resolve(__dirname, "src");
module.exports = {
entry: {
"styles": path.resolve(__dirname, "src/scss/main.scss")
},
output: {
clean: true,
path: path.resolve(__dirname, "dist"),
publicPath: "",
},
module: {
rules: [ ... ]
},
plugins: [
// Extract the generated CSS from the JS-CSS into actual CSS.
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css"
}),
]
}
如果相关,这是我将 SCSS 编译为 CSS 的规则:
{
test: /\.scss$/,
use: [
// Extract the generated CSS from the JS-CSS into actual CSS.
{
loader: MiniCssExtractPlugin.loader,
options: {
esModule: false,
}
},
{
loader: 'css-loader',
},
// Compile SCSS to JS-CSS.
{
loader: 'sass-loader',
options: {
sassOptions: {},
sourceMap: true
}
}
]
},
这是我目前的资产规则:
{
test: /\.(jpg|png|svg)$/,
type: "asset/resource",
generator: {
// Do not copy the asset to the output directory.
emit: false,
// Rewrite asset filesystem path to be relative to the asset public path.
filename: (pathData) => {
const file = pathData.module.resource;
if (file.startsWith(`${src_dir}/`)) {
return path.relative(src_dir, file);
}
throw new Error(`Unexpected asset path: ${file}`);
},
// The public path (prefix) for assets.
publicPath: "/a/",
}
}
如何将新规则配置为仅内联logo.svg
?根据我收集到的信息,我需要以下内容:
{
test: /\.svg$/,
type: "asset/inline",
// ... some unknown webpack-fu.
},
但是我从这里做什么?webpack文档非常缺乏任何有用的 CSS 示例。这不是某个 JavaScript 应用程序,其中每个资产都使用require()
. 我只使用 SCSS/CSS。
解决方案
我很接近。您可以做的是将?inline
作为查询参数添加到 SVG URL:
/* src/scss/main.scss */
.logo {
background-image: url('/images/logo.svg?inline');
}
添加/inline/
为内联规则的resourceQuery :
{
test: /\.svg$/,
type: "asset/inline",
// Inline assets with the "inline" query parameter.
resourceQuery: /inline/,
},
并用oneOf包装资产规则,以便在一般资源规则之前优先考虑内联标记的 SVG:
module.exports = {
// ...
module: {
rules: [
// ...
{oneOf: [
{
test: /\.svg$/,
type: "asset/inline",
// ...
},
{
test: /\.(jpg|png|svg)$/,
type: "asset/resource",
// ...
},
]},
// ...
]
},
// ...
};
推荐阅读
- python - 使用 django 创建通知
- asp.net-core - 为什么要为两种类型的客户端应用程序使用令牌/OIDC 服务器?
- r - linux集群上Rscript中的R getopt包返回错误
- javascript - FileMaker 网页浏览器
- c# - 为什么老图不来图片框改?Asp.Net Mvc c#
- python - Python - 如何将带有元组的列表转换为具有两个值的字典
- python - 我怎样才能让 discord.py 抓取某人的文本并通过一段代码运行它
- python - 将查询结果从 Big Query python api 保存到 CSV
- javascript - 构建父母和孩子的平面数组的更有效方法
- flutter - 在不单击菜单项的情况下关闭 SelectableText 的上下文菜单