[TOC]
typescript常见问题解决
1. 规则校验类报错
1.1 Cannot find module './img/one.png' or its corresponding type declarations.
在vue3项目中, 使用import引入图片资源的时候,报如图所示的错误,经过确认,引用路径没有问题。
1.1.1 报错原因
在 TypeScript 项目中通过 import
导入图片时出现 Cannot find module
错误,通常是由于 TypeScript 无法识别非代码资源(如 .png
、.jpg
等文件)导致的。
1.1.2 解决方案
1.1.2.1 添加类型声明文件(实测有效)
在项目的src
目录中创建或修改images.d.ts
,声明图片模块类型:
// 示例:src/images.d.ts
declare module '*.png' {
const value: string;
export default value;
}
declare module '*.jpg' {
const value: string;
export default value;
}
// 可扩展其他图片格式(如 .svg、.jpeg、.gif、.bmp、.tif/.tiff、.webp 等)
1.1.2.2 确保声明文件被 TypeScript 识别
检查 tsconfig.json
:确保声明文件路径包含在 include
或 typeRoots
配置中:
{
"compilerOptions": {
"typeRoots": ["./node_modules/@types", "./src/types"]
},
"include": ["src/**/*"]
}
1.1.2.3 验证导入路径
确认图片路径正确且文件存在35。
若使用别名(如
@/assets
),需在tsconfig.json
中配置paths
:{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } } }
1.1.2.4 替代方案(非推荐)
使用
require
:动态导入图片(需配置 Webpack 或 Vite 支持):const imgPath = require('./assets/image.png') as string;
直接使用 URL:将图片放在
public
目录并通过绝对路径引用。