Nuxtでsvgを使いたくてvue-svg-loaderを導入するもVSCodeのVeturと
buildエラーが出て解決に困ったので明記します。
表題のエラー解決方法を今すぐ知りたい方はこちら
https://qiita.com/kawa64372358/items/aa327ea55f7df0d510bc#解決方法
vue-svg-loaderの導入
vue-svg-loader:https://www.npmjs.com/package/vue-svg-loader
これを導入するとSVGファイルをVueコンポーネントとして使用できます。
SVGをインライン化しているのでスタイルを設定できたり、SSRでも問題なく利用できます。
$ yarn add -D vue-svg-loader
nuxt.configに下記を追記
Vue CLIの場合は記述が変わるのでbasic-configurationを確認してください
build: {
extend(config: any, ctx: any) {
// svg
const svgRule = config.module.rules.find((rule: any) => rule.test.test('.svg'));
svgRule.test = /\.(png|jpe?g|gif|webp)$/;
config.module.rules.push({
test: /\.svg$/,
loader: 'vue-svg-loader'
});
}
実際にsvgを読み込みたいcomponentに下記を追記
<template>
<ThreeLinesIcon />
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import ThreeLinesIcon from '~/assets/svg/icons/ThreeLinesIcon.svg';
@Component({
components: {
ThreeLinesIcon
}
})
export default class GlobalNavigation extends Vue {}
</script>
"Cannot find module" with TypeScript [Vetur]
ブラウザにはsvgが通常表示されるも、下記ビルドエラーが発生
Cannot find module '~/assets/svg/icons/ThreeLinesIcon.svg'.
同じような問題がvuejs/veturのissuesにありました
Cannot find module 'xxxx' #762
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
}
}
自分の場合は、すでにcompilerOptionsでpathsを書いていたので関係なさそう・・
解決方法
vue-svg-loaderのissuesに解決方法が書いてありました
"Cannot find module" with Typescript #37
vue-svg-loaderのdocumentationにも書いてありました
https://vue-svg-loader.js.org/faq.html#how-to-use-this-loader-with-typescript
If you want to use this loader in a project that is written in TypeScript, you will get the "Cannot find module" error. To fix that you need to provide a type definition which is needed by TypeScript to know how to handle SVG components.
assetsのsvgを格納しているディレクトリに下記のような型ファイルを追加してあげればいいみたい
declare module '*.svg' {
const content: any;
export default content;
}
無事解決しました。これでbuildも通ります!
参考
Cannot find module '~/components/Card.vue'. Vetur
https://qiita.com/kanzume/items/2ff1be119d7e64089d30