Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 857
Thaledric Avatar asked Oct 28 '25 09:10

Thaledric


2 Answers

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;
}
like image 96
Edgar Quintero Avatar answered Oct 31 '25 00:10

Edgar Quintero


You need just little adjustment to your module declaration for .svg files. Your shims-svg.d.ts file should be:

declare module '*.svg' {

    import { VNode } from 'vue';

    // DON'T DECLARE THIS INSIDE GLOBAL MODULE
    type Svg = VNode;

    const content: Svg;
    export default content;
}

Note that augmentations for the global scope can only be directly nested in external modules or ambient module declarations.

like image 28
Harshal Patil Avatar answered Oct 31 '25 02:10

Harshal Patil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!