javascript - 如何在 Vue 3 中导入 svg?

标签 javascript typescript vue.js svg vuejs3

我试过以下:
https://github.com/visualfanatic/vue-svg-loader/tree/master
但是与 vue-template-compiler 存在版本冲突,因为它在 Vue 2 中使用。
我试过了:
https://github.com/visualfanatic/vue-svg-loader
但我缺少一个特定的 vue 依赖项。
我注意到使用 typescript 有一个警告,您需要声明类型定义文件。但是,我仍然得到“找不到模块 '../../assets/myLogo.svg' 或其相应的类型声明。”
这是我添加的内容:
vue.config.js

module.exports = {
  chainWebpack: (config) => 
  {
    const svgRule = config.module.rule('svg');

    svgRule.uses.clear();

    svgRule
      .use('vue-loader-v16')
      .loader('vue-loader-v16')
      .end()
      .use('vue-svg-loader')
      .loader('vue-svg-loader');
  },
  configureWebpack: process.env.NODE_ENV === 'production' ? {} : {
    devtool: 'source-map'
  },
  publicPath: process.env.NODE_ENV === 'production' ?
    '/PersonalWebsite/' : '/'
}
垫片-svg.d.ts
declare module '*.svg' {
  const content: any;
  export default content;
}
我的组件.vue
<template>
  <div>
     <MyLogo />
  </div>
</template>

<script lang="ts">
import * as MyLogo from "../../assets/myLogo.svg";

export default defineComponent({
  name: "MyComponent",
  components: {
    MyLogo
  },
  props: {
    
  },
  setup(props)
  {
    return {
      props
    };
  }
});


</script>

最佳答案

实际上,Vue CLI 开箱即用地支持 SVG。它使用 file-loader内部。您可以通过在终端上运行以下命令来确认它:

vue inspect --rules
如果列出了“svg”(应该是),那么您所要做的就是:
<template>
  <div>
    <img :src="myLogoSrc" alt="my-logo" />
  </div>
</template>

<script lang="ts">
  // Please just use `@` to refer to the root "src" directory of the project
  import myLogoSrc from "@/assets/myLogo.svg";

  export default defineComponent({
    name: "MyComponent",

    setup() {
      return {
        myLogoSrc
      };
    }
  });
</script>
所以不需要任何第三方库——也就是说,如果你的纯粹目的只是显示 SVG。
当然,为了满足 TypeScript 编译器的类型声明:
declare module '*.svg' {
  // It's really a string, precisely a resolved path pointing to the image file
  const filePath: string;

  export default filePath;
}

关于javascript - 如何在 Vue 3 中导入 svg?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65100281/

相关文章:

javascript - 如何简单地编写Ajax脚本(删除重复代码)?

javascript - Angularjs 使用 momentjs 获取总时间

javascript - Node WebKit 和 SerialPort

javascript - V-for 单击所有按钮而不是仅单击一个按钮

vue.js - VueJS : scope. 通知不是函数

javascript - JS 中的依赖跟踪功能

javascript - 当语句成立时运行函数

reactjs - typescript React/Redux : Argument of type 'typeof MyClass' is not assignable to parameter of type 'ComponentType<...'

reactjs - 测试从本地 JSON 文件中获取一些数据的异步操作创建器

javascript - JHipster - 函数完成后执行代码