webpack - 如何使用 Webpack 5 有选择地将 SVG 内联到 CSS 中?

标签 webpack css-loader sass-loader webpack-5

我正在使用 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
            }
        }
    ]
},

这是我当前的 Assets 规则:

{
    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 示例。这不是某个 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 包装 Assets 规则在一般资源规则之前优先考虑内联标记的 SVG:

module.exports = {
    // ...
    module: {
        rules: [
            // ...
            {oneOf: [
                {
                    test: /\.svg$/,
                    type: "asset/inline",
                    // ...
                },
                {
                    test: /\.(jpg|png|svg)$/,
                    type: "asset/resource",
                    // ...
                },
            ]},
            // ...
        ]
    },
    // ...
};

关于webpack - 如何使用 Webpack 5 有选择地将 SVG 内联到 CSS 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69408473/

相关文章:

javascript - Nuxt.js:css-loader 的问题,它从 font-family 中删除引号

node.js - 使用 NODE_MODULE_VERSION 64 针对不同的 Node.js 版本编译。此版本的 Node.js 需要 NODE_MODULE_VERSION 67

typescript - 使用 Webpack 根据模式要求不同的应用程序配置文件

javascript - 尝试在我的 React 应用程序中使用 webpack。获取 "error Command failed with exit code 2."

javascript - 在 VueAxios 中从 .env 设置 baseURL

css-loader - 如何跳过 Webpack 4 中的 Javascript 输出?

javascript - 带有 sourcemaps 和 url 语句的 Webpack sass 加载器

reactjs - React 故事书 sass-loader 导入 node_modules

node.js - 如何使用 node.js 从服务器端刷新浏览器?

css - 如何在 webpack 中禁用一个文件的 css 模块