Angular项目ng-build不识别子目录tsconfig.json配置问题咨询
问题原因
Angular CLI的ng build构建流程并不支持TypeScript的Project References(即根tsconfig中的references配置)。它会忽略子目录的tsconfig文件,仅使用angular.json中指定的tsconfig(通常是tsconfig.app.json)来编译所有源码文件,这就是为什么你的配置在tsc命令下生效,但ng build直接跳过严格检查的原因。
可行解决方案
方案1:拆分严格检查代码为独立Angular Library
将需要开启strictNullChecks的目录封装为一个Angular Library,利用Library独立的tsconfig配置实现差异化检查:
- 使用Angular CLI创建Library:
ng generate library strict-features - 在Library的
projects/strict-features/tsconfig.lib.json中开启strictNullChecks:{ "extends": "../../tsconfig.json", "compilerOptions": { "strictNullChecks": true, // 其他Library相关配置 }, "include": ["src/**/*.ts"] } - 主应用的根tsconfig保持
strictNullChecks: false,通过导入Library的模块使用严格检查后的代码。 - 运行
ng build时,CLI会单独编译Library并应用其严格配置,主应用则使用自身的宽松配置。
方案2:自定义编译流程结合CLI
如果不想拆分项目,可以通过先编译严格目录再执行CLI构建的方式实现:
- 子目录tsconfig(如
src/app/strict/tsconfig.json)配置:{ "extends": "../../tsconfig.json", "compilerOptions": { "strictNullChecks": true, "outDir": "../../../dist/strict-output", "rootDir": "./", "noEmit": false }, "include": ["./**/*.ts"] } - 在根tsconfig中添加
references指向子目录配置:{ "references": [{"path": "./src/app/strict"}] } - 修改
angular.json的build配置,排除原严格目录的ts文件,避免CLI重复编译:{ "projects": { "your-app": { "architect": { "build": { "options": { "exclude": ["src/app/strict/**/*.ts"], // 其他配置 } } } } } } - 编写自定义脚本(如
package.json的scripts):
执行{ "scripts": { "build": "tsc --build && ng build" } }npm run build即可先编译严格目录,再构建主应用。
方案3:临时忽略错误,逐步全局开启
如果拆分成本较高,可以先全局开启strictNullChecks,再用TypeScript注释临时屏蔽未修复的错误:
- 在根tsconfig中开启
strictNullChecks: true - 对暂时无法修复的错误,在代码中添加
// @ts-ignore忽略单条错误,或// @ts-nocheck忽略整个文件的检查,逐步修复后移除注释。
内容的提问来源于stack exchange,提问作者msteel9999
相关产品推荐
相关产品推荐

