You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue CLI默认用file-loader处理SVG,替换为svg-sprite-loader后不生效求助

Fixing SVG Sprite Loader Not Taking Effect in Vue CLI

Hey there, I know exactly what's going on here—your custom SVG loader config isn't working because Vue CLI's default file-loader rule for SVGs is still active, and it's taking priority over your new rules. Here's how to fix it properly:

Vue CLI uses webpack-chain under the hood, which lets you modify the existing config chain directly. This is cleaner than overriding the entire rules array:

module.exports = {
  chainWebpack: config => {
    // Clear the default SVG rule's loaders first
    config.module.rule('svg').uses.clear();

    // Add your custom SVG loaders in order
    config.module.rule('svg')
      .test(/\.(svg)(\?.*)?$/)
      // Add svg-sprite-loader
      .use('svg-sprite-loader')
        .loader('svg-sprite-loader')
        .options({
          name: '[name]-[hash:7]',
          prefixize: true
        })
        .end()
      // Add svg-fill-loader
      .use('svg-fill-loader')
        .loader('svg-fill-loader')
        .end()
      // Add svgo-loader
      .use('svgo-loader')
        .loader('svgo-loader')
        .end();
  }
};

Method 2: Modify configureWebpack

If you prefer sticking with configureWebpack, you need to filter out the default SVG rule before adding your own:

module.exports = {
  configureWebpack: config => {
    // Filter out the default rule that handles SVGs with file-loader
    config.module.rules = config.module.rules.map(rule => {
      if (rule.test && rule.test.test('.svg')) {
        // Exclude SVGs from the default rule
        return { ...rule, exclude: /\.svg$/ };
      }
      return rule;
    });

    // Add your custom SVG processing rule
    config.module.rules.push({
      test: /\.(svg)(\?.*)?$/,
      use: [
        {
          loader: 'svg-sprite-loader',
          options: {
            name: '[name]-[hash:7]',
            prefixize: true
          }
        },
        'svg-fill-loader',
        'svgo-loader'
      ]
    });
  }
};

Quick Checks to Ensure It Works

  • Make sure you've installed all required loaders:
    npm install svg-sprite-loader svg-fill-loader svgo-loader --save-dev
    
  • When importing SVGs (e.g., import MyIcon from './my-icon.svg'), you should now get a sprite-ready object instead of a file URL.

内容的提问来源于stack exchange,提问作者Michael Giovanni Pumo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:00:00