导入 *.svg 模块会引发 Typescript 错误:“找不到模块......" [英] Importing a *.svg module raises Typescript error : "Cannot find module ..."
问题描述
这是一个使用 @vue/cli
制作的 Web 应用程序.我想使用 vue-svg-loader
将内联 Svg 作为 vue 组件加载.
It's a web application made with @vue/cli
.
I want to use vue-svg-loader
to load inline Svg as vue components.
正如 vue-svg-loader 安装指南所说,我把这个vue.config.js
中的代码:
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');
},
};
并使用 import ViwanMap from '@/assets/ViwanMap.svg';
导入我的 Svg 文件.
and import my Svg file with import ViwanMap from '@/assets/ViwanMap.svg';
.
另外,我在我的 src/
文件夹中创建了一个 shims-svg.d.ts
包含:
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;
}
另外,还有我的 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"
]
}
编译过程引发此错误:
ERROR in <MY_PROJECT_ROOT>/src/views/Home.vue
12:22 Cannot find module '@/assets/ViwanMap.svg'.
然而,webpack 进程似乎可以工作,因为 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 :)
推荐答案
Harshal Patil 的回答有效,但我使用了这里的内容:官方文档
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;
}
这篇关于导入 *.svg 模块会引发 Typescript 错误:“找不到模块......"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!