简体   繁体   English

Webpack 无法解析 svg

[英]Webpack can't resolve svg

Webpack can't resolve svg when I try to use my svg as a background with relative path当我尝试使用我的 svg 作为具有相对路径的背景时,Webpack 无法解析 svg

image background-image: url('./checkmark.svg');

webpack give me 'can't resolve' error webpack 给我“无法解决”错误

But absolute path is ok.但是绝对路径是可以的。

background-image: url(C:\Users\leo\Desktop\project\hotel\src\components\checkbox-list\__menu\checkbox-list__checkbox\checkmark.svg);

Actualy my config rules:实际上我的配置规则:

module: {
  rules: [{
      test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
      type: 'asset/resource',
    },
    {
      test: /\.scss$/,
      use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
    },
    {
      test: /\.(woff(2)?|eot|ttf|otf|svg)$/,
      type: 'asset',
    },
    {
      test: /\.pug$/,
      loader: 'pug-loader',
      options: {
        pretty: true,
      },
    },
  ],
},

i think you need to use url_loader within webpack to load svgs the same way you loading scss.我认为您需要在 webpack 中使用url_loader来加载 svg,就像加载 scss 一样。 and then import it in your code and use it in your component or file.然后将其导入您的代码并在您的组件或文件中使用它。

npm i svg-url-loader --save-dev

{
        test: /\.svg$/,
        use: [
          {
            loader: 'svg-url-loader',
            options: {
              limit: 10000,
            },
          },
        ],
      },

vue example srouce vue 示例资源

<template>
  <div>
    <InlineSVG />
    <div class="external-svg" />
  </div>
</template>

<script>
import InlineSVG from './public/inline.svg';

export {
  components: {
    InlineSVG,
  },
};
</script>

<style>
.external-svg {
  background-image: url("./public/external.svg"); 
}
</style>

workaround no loader解决方法没有加载程序

if you are using it into css directly and then css loaded using webpack than bare in mind that the link should be working in dist too, so you can provide the file manually in dist with the same link as in src如果您直接将它使用到 css 中,然后使用 webpack 加载 css ,请记住链接也应该在 dist 中工作,因此您可以在 dist 中手动提供与链接相同的文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM