Angular项目导入JSZip时出现TS2403类型冲突错误求助
问题场景
已执行npm install jszip确认包安装正常,但使用import * as JSZip from 'jszip';导入时出现类型冲突错误:
Error: node_modules/@types/node/globals.d.ts:72:13 - error TS2403: Subsequent variable declarations must have the same type. Variable 'AbortSignal' must be of type '{ new (): AbortSignal; prototype: AbortSignal; abort(reason?: any): AbortSignal; timeout(milliseconds: number): AbortSignal; }', but here has type '{ new (): AbortSignal; prototype: AbortSignal; }'.
72 declare var AbortSignal: {node_modules/typescript/lib/lib.dom.d.ts:2071:13 2071 declare var AbortSignal: { 'AbortSignal' was also declared here.
当前版本:Angular 15.1.1、TypeScript 4.9.6、jszip 3.10.1
解决方案
方案1:明确指定项目依赖的类型包
修改项目根目录下的tsconfig.json,在compilerOptions中添加types字段,仅引入需要的类型包,避免自动加载@types/node的全局类型导致冲突:
{ "compilerOptions": { // 保留原有其他配置 "types": ["jszip"] } }
若项目需要其他类型包(如jest),可在数组中追加对应的包名。
方案2:限制类型查找范围
如果项目必须依赖@types/node,可通过typeRoots字段指定类型包的查找目录,隔离冲突的全局类型:
{ "compilerOptions": { // 保留原有其他配置 "typeRoots": ["./node_modules/@types/jszip", "./node_modules/@types/angular"] } }
方案3:使用ESM风格导入
更换导入方式为ESM格式,同时确保TypeScript配置支持模块交互:
import JSZip from 'jszip';
需保证tsconfig.json的compilerOptions中,module设置为ES2020或更高版本,esModuleInterop设置为true。
内容的提问来源于stack exchange,提问作者Brofo

