vue-svg-loader 不相容 vue 3。要導(dǎo)入 svg 並將其用作元件,只需將文件內(nèi)容包裹在 'template' 中
在元件中:
<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>`; };
實際上,Vue CLI已經(jīng)原生支援SVG。它內(nèi)部使用file-loader。您可以透過在終端機上執(zhí)行以下命令來確認(rèn):
vue inspect --rules
如果「svg」被列出(應(yīng)該會被列出),那麼您只需要:
<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>
因此,如果您的目的只是顯示SVG,那麼不需要任何第三方程式庫。
當(dāng)然,為了滿足TypeScript編譯器的型別宣告要求:
declare module '*.svg' { // 它實際上是一個字符串,精確地說是指向圖像文件的解析路徑 const filePath: string; export default filePath; }