TurboRepo 存在TypeScript错误仍可构建的问题排查
TurboRepo 单仓项目中TypeScript类型错误未触发构建失败的问题
项目结构
apps |- app1 |- app2 packages |- lib | .... some files |- tsconfig.json |- package.json
问题现象
在lib包中创建了一个存在明显TypeScript类型错误的文件:
const a: String = 23; console.log(a);
编辑器编辑时能正常检测到该错误,但在应用中引入该文件后,执行npm run build项目仍能正常完成构建(未设置任何忽略错误的选项)。只有将该错误文件放在应用目录下,构建才会失败并抛出正确错误信息。
相关配置
lib包的tsconfig.json
{ "compilerOptions": { "target": "es2016", "module": "commonjs", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "noEmit": true, "incremental": true, "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "moduleResolution": "node" }, "include": ["."], "exclude": ["dist", "build", "node_modules"] }
应用目录的tsconfig.json
{ "compilerOptions": { "target": "es2016", "module": "commonjs", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "noEmit": true, "incremental": true, "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "moduleResolution": "node" }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] }
问题原因
skipLibCheck的影响:应用tsconfig中skipLibCheck: true会让TypeScript跳过对外部依赖的类型检查。当从lib包导入代码时,TypeScript将其视为外部依赖,不会主动扫描源码中的类型错误。lib包的noEmit配置:lib包设置了noEmit: true,不会生成类型声明文件(.d.ts)。应用无法通过声明文件感知lib的类型问题,且skipLibCheck跳过了对lib源码的检查。- TurboRepo构建流程:默认情况下,TurboRepo未配置依赖检查,构建应用前不会自动执行
lib包的类型检查任务,导致lib的错误不会被触发检测。
解决方案
方案1:为lib包添加独立类型检查任务
在lib包的package.json中添加类型检查脚本:
{ "scripts": { "type-check": "tsc --noEmit" } }
在项目根目录的turbo.json中配置任务依赖,确保构建应用前先执行lib的类型检查:
{ "pipeline": { "type-check": { "dependsOn": ["^type-check"] }, "build": { "dependsOn": ["type-check", "^build"] } } }
执行npm run build时会先检查lib包的类型错误,有错误则终止构建。
方案2:让lib包生成类型声明文件
修改lib包的tsconfig,开启类型声明生成:
{ "compilerOptions": { // ...其他配置 "noEmit": false, "declaration": true, "declarationDir": "./dist" } }
在lib包的package.json中配置入口字段:
{ "main": "./dist/index.js", "types": "./dist/index.d.ts", "scripts": { "build": "tsc" } }
在turbo.json中配置应用构建依赖lib的构建任务,这样lib源码有错误时会导致声明文件生成失败,进而终止应用构建。
方案3:修改应用tsconfig,包含lib包检查(不推荐)
修改应用的tsconfig,将lib包纳入检查范围:
{ "compilerOptions": { // ...其他配置 "skipLibCheck": false, "paths": { "@your-project/lib": ["../packages/lib"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "../packages/lib/**/*.ts"], "exclude": ["node_modules"] }
此方式会增加应用构建时间,不符合单仓职责分离原则,仅作为临时方案使用。
内容的提问来源于stack exchange,提问作者Vipul Rajan
相关产品推荐
相关产品推荐

