【发布时间】:2021-11-23 06:07:00
【问题描述】:
我正在使用 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 documentation 非常缺乏任何有用的 CSS 示例。这不是使用 require() 导入每个资产的 JavaScript 应用程序。我只使用 SCSS/CSS。
【问题讨论】:
标签: webpack css-loader sass-loader webpack-5