如何仅用allowJs做类型检查,避免编译第三方JS库?
利用第三方JS库的JSDoc做类型检查但不编译输出的方案
方案1:拆分tsconfig配置文件(推荐)
通过拆分两个tsconfig,分别处理类型检查和编译构建,既复用公共配置,又精准实现需求:
- 创建公共基础配置文件
tsconfig.base.json,存放通用编译选项:
{ "compilerOptions": { "target": "ES2020", "module": "CommonJS", "strict": true, "outDir": "./dist", // 其他你需要的公共配置 } }
- 创建类型检查专用配置
tsconfig.check.json,继承基础配置并开启JS类型检查:
{ "extends": "./tsconfig.base.json", "compilerOptions": { "allowJs": true, "noEmit": true // 只做类型检查,不输出任何文件 }, "include": [ "src/**/*", "node_modules/[你的目标库]/**/*.js" // 包含库的JS文件以读取JSDoc ] }
- 创建编译构建专用配置
tsconfig.build.json,继承基础配置并聚焦源码编译:
{ "extends": "./tsconfig.base.json", "compilerOptions": { "allowJs": false // 无需编译JS文件 }, "include": ["src/**/*"], // 仅编译你的业务源码 "exclude": ["node_modules"] }
- 给目标库添加极简类型声明文件(比如
types/[库名].d.ts),避免编译阶段报错:
declare module "[你的目标库]";
- 在
package.json中添加脚本简化执行:
{ "scripts": { "type-check": "tsc --project tsconfig.check.json", "build": "tsc --project tsconfig.build.json" } }
执行npm run type-check完成类型检查,执行npm run build编译业务代码,全程无需添加// @ts-ignore。
方案2:通过自定义类型声明引入JSDoc
如果不想拆分配置文件,可以通过自定义类型声明让TS读取库的JSDoc,同时避免编译输出库文件:
- 项目根目录创建
types/[库名]/index.d.ts,替换为库的实际入口路径:
/// <reference path="../../node_modules/[库名]/dist/index.js" /> declare module "[库名]" { export * from "../../node_modules/[库名]/dist/index.js"; }
- 修改
tsconfig.json配置,让TS识别自定义类型并开启JS类型检查:
{ "compilerOptions": { "strict": true, "allowJs": true, "typeRoots": ["./types", "./node_modules/@types"], // 优先读取自定义类型 "skipLibCheck": false // 确保TS检查库的类型 }, "include": ["src/**/*"], // 仅包含业务源码,不包含库文件 "exclude": ["node_modules"] }
TS会通过reference path读取库的JS文件JSDoc生成类型,编辑器能正常获取提示,类型检查生效,编译时只会输出你的业务代码,不会处理node_modules中的库文件。
内容的提问来源于stack exchange,提问作者Raphael Schweikert
相关产品推荐
相关产品推荐

