首页 > 解决方案 > 捆绑后 SVG 图标不呈现(webpack)

问题描述

我正在使用文件加载器插件来加载我的图像,好吧,所有图像在 webpack 构建后都可以正确显示,但是我的 SVG 图标没有出现在页面上。文件夹结构正确,所有图像都相同。并且没有返回任何类型的错误

const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');

module.exports = {
  entry: './src/js/controller.js',
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },

  module: {
    rules: [
      //Parsing Styles
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          MiniCssExtractPlugin.loader,
          // Translates CSS into CommonJS
          "css-loader",
          // Compiles Sass to CSS
          "sass-loader",
        ],
      },
      //Parsing Images
      {
        test: /\.(png|jpe?g|gif|svg)$/i,
        use: [ 
          { 
            loader: 'file-loader',
            options: { name: '[path][name].[ext]' },
          },
        ]
      },
     
    ],
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html',
      filename: 'index.html'
    }),

    new MiniCssExtractPlugin({
      filename: 'style.css'
    })
  ]
}

我的图标直接嵌入到 html 中。

<button class="btn search__btn">
  <svg class="search__icon">
    <use href="src/img/icons.svg#icon-search"></use>
  </svg>
  <span>Search</span>
</button>

我的文件夹结构如下:

Develop

src/
├── img/
│   ├── ...
│   └──  icons.svg
├───js/
│    └──index.js
├───sass/
│   ├──...
│   └──main.scss
index.html

Build

dist/
├── src/
│   └── img/
│       ├──...
│       └──icons.svg
style.css
index.js
index.html

标签: javascriptwebpack

解决方案


尝试安装 npm install @svgr/webpack ,然后在 webpack 中添加以下规则

{
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      },
    

推荐阅读