为何TypeScript可正常导入本地JS文件,却报错node_modules中的JS模块?
为什么TypeScript能正常导入本地JS文件,却导入node_modules里的JS文件时报错?
问题描述
TypeScript编译器可以正常导入本地目录中的JS文件,但直接导入node_modules中的JS文件时,会抛出找不到声明文件的错误。
代码示例
import { t2 } from "./t1.js" t2.hello(); import { mat4 } from "./node_modules/gl-matrix/esm/index.js"; mat4.create();
报错信息
main.ts:4:22 - error TS7016: Could not find a declaration file for module './node_modules/gl-matrix/esm/index.js'. '/.../node_modules/gl-matrix/esm/index.js' implicitly has an 'any' type. 4 import { mat4 } from "./node_modules/gl-matrix/esm/index.js"; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
注释最后两行代码后,编译器可正常编译。
复现步骤
npm install --save-dev typescript gl-matrix
tsconfig.json配置
{ "compilerOptions": { "target": "ES2022", "module": "ES2022", "outDir": "./obj", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "allowJs": true } }
模拟文件
t1.js(模拟gl-matrix中index.js的内容):
import * as t2 from "./t2.js" export { t2 };
t2.js(模拟gl-matrix中mat4.js的内容):
export function hello() { return "hello"; }
原因分析
TypeScript对本地JS文件和node_modules中的JS文件采用了不同的处理逻辑:
- 本地JS文件:开启
allowJs: true后,TypeScript会自动解析本地JS文件的导出内容,生成临时的类型推断信息,即使没有显式的.d.ts声明文件,也能通过类型检查(strict模式下不会因为隐式any报错)。 - node_modules中的JS文件:TypeScript默认不会对
node_modules内的文件进行自动类型推断,而是期望模块自带声明文件或安装对应的@types包。当你通过相对路径直接导入node_modules里的文件时,TypeScript不会将其识别为标准npm包,不会去查找该包的类型声明,因此抛出“找不到声明文件”的错误。
解决方法
方法1:使用包名导入(推荐)
不要直接通过相对路径导入node_modules内的文件,而是使用包名导入,让TypeScript自动查找模块的类型声明:
// 替换原导入语句 import { mat4 } from 'gl-matrix/esm';
方法2:手动添加声明文件
如果必须通过相对路径导入,可以在项目中创建一个自定义声明文件(比如gl-matrix.d.ts),手动声明模块类型:
declare module './node_modules/gl-matrix/esm/index.js' { export const mat4: { create: () => number[]; // 根据需要补充其他方法的类型定义 }; }
方法3:关闭隐式any检查(不推荐)
在tsconfig.json中设置noImplicitAny: false,但这会关闭strict模式下的隐式any类型检查,可能导致其他类型问题:
{ "compilerOptions": { // ...其他配置 "noImplicitAny": false } }
内容的提问来源于stack exchange,提问作者n0rd
相关产品推荐
相关产品推荐

