Search code examples
typescriptsvgvue.js

Importing a *.svg module raises Typescript error : "Cannot find module ..."


It's a web application made with @vue/cli. I want to use vue-svg-loader to load inline Svg as vue components.

As vue-svg-loader installation guide says, I put this code in vue.config.js :

module.exports = {
  chainWebpack: (config) => {
    const svgRule = config.module.rule('svg');
    svgRule.uses.clear();
    svgRule
      .use('vue-svg-loader')
      .loader('vue-svg-loader');
  },
};

and import my Svg file with import ViwanMap from '@/assets/ViwanMap.svg';.

Also, I created a shims-svg.d.ts in my src/ folder containing :

import { VNode } from 'vue';
declare global {
  type Svg = VNode; // With vue-svg-loader, imported svg is a Vue component.
}

declare module '*.svg' {
  const content: Svg;
  export default content;
}

Also, there is my tsconfig.js :

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

The compilation process raises this error :

ERROR in <MY_PROJECT_ROOT>/src/views/Home.vue
12:22 Cannot find module '@/assets/ViwanMap.svg'.

However, the webpack process seems to work, as the svg shows up in my app. It seems to be only a typescript issue. Do you know what is the problem ? Thank you :)


Solution

  • Harshal Patil's answer worked, except I used what was here instead: Official Documentation

    declare module '*.svg' {
      import Vue, {VueConstructor} from 'vue';
      const content: VueConstructor<Vue>;
      export default content;
    }