簡體   English   中英

Webpack 5 使用html-loader加載svgs

[英]Webpack 5 use html-loader to load svgs

我最近升級到 Webpack 5 並且我的 html-loader 不再加載 svg 文件並內聯它們。

這是我在 webpack 中的 svg 規則

{
  test: /\.svg$/,
  use: [
    {
       loader: 'html-loader',
       options: {
           minimize: true,
       },
    },
  ],
},

無論我如何嘗試導入它,它似乎只是創建一個文件而不給我一串 HTML。

import mySvg from "../path/to/my.svg"

let mySvg = require("../path/to/my.svg").default;

// output = "/build/path/my.svg"
// output I want = "<svg>...."

它過去沒有給我幾個構建文件,而是將它們內聯在我的 JS 中。

幫助將不勝感激。

svg-inline-loader可以實現相同的(確認工作)。

我在https://survivejs.com/webpack/loading/images/#loading-svgs列出了加載 SVG 的其他選項。

我使用posthtmlposthtml-inline-svg插件。

const postHtml = require('posthtml');
const postHtmlInlineSvg = require('posthtml-inline-svg');

{
  test: /\.html$/,
  use: {
    loader: 'html-loader',
    options: {
      esModule: false,
      preprocessor: async (content, loaderContext) => {
        try {
          return await postHtml(postHtmlInlineSvg({ cwd: loaderContext.context, tag: 'icon', attr: 'src' }),).process(content)).html;
        } catch (error) {
          loaderContext.emitError(error);
          return content;
        }
      },
    },
  },
},

如果您使用HtmlWebpackPlugin ,則HtmlWebpackInlineSVGPlugin可用於內聯 svg。

以下是 webpack 配置的相關部分,以實現相同的目的:

{
  // ...
  module: {
    rules: [
      {
        test: /\.html/,
        loader: "html-loader",
      },
      // ...
    ],
  },
  plugins: [
    new HtmlWebpackPlugin(),
    new HtmlWebpackInlineSVGPlugin({
      inlineAll: true,
    }),
    // ...
  ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM