导入 *.svg 模块会引发 Typescript 错误:“找不到模块......”

Tha*_*ric 1 svg typescript vue.js

这是一个使用@vue/cli. 我想用来vue-svg-loader加载内联 Svg 作为 vue 组件。

正如vue-svg-loader 安装指南所说,我把这段代码放在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');
  },
};
Run Code Online (Sandbox Code Playgroud)

并导入我的 Svg 文件import ViwanMap from '@/assets/ViwanMap.svg';

另外,我shims-svg.d.ts在我的src/文件夹中创建了一个包含:

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;
}
Run Code Online (Sandbox Code Playgroud)

另外,还有我的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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

编译过程引发此错误:

ERROR in <MY_PROJECT_ROOT>/src/views/Home.vue
12:22 Cannot find module '@/assets/ViwanMap.svg'.
Run Code Online (Sandbox Code Playgroud)

但是,webpack 进程似乎有效,因为 svg 出现在我的应用程序中。这似乎只是一个打字稿问题。你知道是什么问题吗?谢谢 :)

Har*_*til 6

您只需对.svg文件的模块声明稍作调整。您的shims-svg.d.ts文件应该是:

declare module '*.svg' {

    import { VNode } from 'vue';

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

    const content: Svg;
    export default content;
}
Run Code Online (Sandbox Code Playgroud)

请注意,全局范围的扩充只能直接嵌套在外部模块或环境模块声明中。


Edg*_*ero 6

Harshal Patil 的回答有效,但我使用了这里的内容:官方文档

declare module '*.svg' {
  import Vue, {VueConstructor} from 'vue';
  const content: VueConstructor<Vue>;
  export default content;
}
Run Code Online (Sandbox Code Playgroud)

  • 我把它放在 `shims-svg.d.ts` 中,效果很好 (3认同)