[英]How do I import an svg in Vue 3?
我试过以下: 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。 它在内部使用文件加载器。 您可以通过在终端上运行以下命令来确认它:
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;
}
不能肯定地说,因为我没有尝试过 ts,但正如这里发布的那样
这应该工作。
declare module '*.svg' {
import type { DefineComponent } from 'vue';
const component: DefineComponent;
export default component;
}
我看到你正在使用:
import * as MyLogo from "../../assets/myLogo.svg";
我认为应该是:
import MyLogo from "../../assets/myLogo.svg";
来自全新安装的示例 vue.js 3.2:
<img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125"/>
vue-svg-loader 与 vue 3 不兼容。要导入 svg 并将其用作组件,只需将文件内容包装在“模板”中
在组件中:
<template>
<div class="title">
<span>Lorem ipsum</span>
<Icon />
</div>
</template>
<script>
import Icon from '~/common/icons/icon.svg';
export default {
name: 'PageTitle',
components: { Icon },
};
</script>
Webpack:
{
test: /\.svg$/,
use: ['vue-loader', path.resolve(__dirname, 'scripts/svg-to-vue.js')],
}
脚本/svg-to-vue.js:
module.exports = function (source) {
return `<template>\n${source}\n</template>`;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.