P粉6765887382023-08-24 00:48:35
vue-svg-loader is not compatible with vue 3. To import an svg and use it as a component, just wrap the file contents in 'template'
In component:
<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')], }
scripts/svg-to-vue.js:
module.exports = function (source) { return `<template>\n${source}\n</template>`; };
P粉5879700212023-08-24 00:34:09
In fact, Vue CLI already supports SVG natively. It uses file-loader internally. You can confirm by running the following command on the terminal:
vue inspect --rules
If "svg" is listed (it should be), then you only need to:
<template>
<div>
<img :src="myLogoSrc" alt="my-logo" />
</div>
</template>
<script lang="ts">
// 请使用`@`来引用项目的根目录“src”
import myLogoSrc from "@/assets/myLogo.svg";
export default defineComponent({
name: "MyComponent",
setup() {
return {
myLogoSrc
};
}
});
</script>
So if your purpose is just to display SVG, you don't need any third-party libraries.
Of course, in order to satisfy the TypeScript compiler’s type declaration requirements:
declare module '*.svg' {
// 它实际上是一个字符串,精确地说是指向图像文件的解析路径
const filePath: string;
export default filePath;
}