如何为旧版CommonJS依赖生成模块名正确的TS类型声明文件
你直接将单个入口文件传给tsc并使用--outFile输出时,tsc会以入口文件的文件名作为模块名生成声明,因此你拿到的是declare module "index"而非你需要的包名,可通过以下方法解决:
解决方案
方案1:调整tsc命令参数,匹配目录结构
先创建与包名一致的目录层级,再执行tsc编译,生成的声明会自动使用正确的包名:
# 创建和包名匹配的临时目录结构 mkdir -p tmp/aabb-3d cp node_modules/aabb-3d/index.js tmp/aabb-3d/ # 执行编译指定根目录和声明输出路径 tsc tmp/aabb-3d/index.js \ --allowJs \ --declaration \ --emitDeclarationOnly \ --rootDir tmp \ --declarationDir types # 可选:清理临时目录 rm -rf tmp
方案2:生成后自动替换模块名
可以直接在原有命令后追加字符串替换逻辑,适合批量处理多个旧依赖:
Unix/macOS 环境:
tsc node_modules/aabb-3d/index.js \ --allowJs \ --declaration \ --emitDeclarationOnly \ --outFile types/aabb-3d/index.d.ts \ && sed -i '' 's/declare module "index"/declare module "aabb-3d"/' types/aabb-3d/index.d.ts
Windows PowerShell 环境:
tsc node_modules/aabb-3d/index.js --allowJs --declaration --emitDeclarationOnly --outFile types/aabb-3d/index.d.ts; ((Get-Content types/aabb-3d/index.d.ts) -replace 'declare module "index"', 'declare module "aabb-3d"') | Set-Content types/aabb-3d/index.d.ts
方案3:使用专门的dts生成工具
针对无类型的npm包,官方dts-gen工具生成的声明默认使用正确的包名,使用更简单:
npx dts-gen -m aabb-3d -o types/aabb-3d/index.d.ts
后续配置
生成类型后需要在项目tsconfig.json中添加自定义类型目录的路径,确保TS可以识别到你生成的声明:
{ "compilerOptions": { "typeRoots": [ "./node_modules/@types", "./types" ] } }
内容的提问来源于stack exchange,提问作者fenomas
相关产品推荐
相关产品推荐

