LoginSignup
20
9

More than 5 years have passed since last update.

【Vue/TypeScript】vue-svg-loaderのbuildエラーを解決

Last updated at Posted at 2019-05-01

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を確認してください

nuxt.config.ts
  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に下記を追記

GlobalNavigatioon.vue
<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'.
スクリーンショット 2019-04-30 19.55.02.png

Veturにもエラーが出ています
スクリーンショット 2019-04-30 21.06.52.png

同じような問題がvuejs/veturのissuesにありました
Cannot find module 'xxxx' #762

tsconfig.json
{
"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を格納しているディレクトリに下記のような型ファイルを追加してあげればいいみたい

index.d.ts
declare module '*.svg' {
  const content: any;
  export default content;
}

無事解決しました。これでbuildも通ります!

参考

Cannot find module '~/components/Card.vue'. Vetur
https://qiita.com/kanzume/items/2ff1be119d7e64089d30

20
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
9