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>`; };
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; }