Angular编译器ngc为何依赖tsconfig.json?与TypeScript编译器有何关联?
Great question—this is a common point of confusion when getting started with Angular's AOT compilation, so let's break it down clearly:
1. ngc is a superset of the TypeScript compiler (tsc)
Angular's ngc (short for Angular Compiler) isn't a completely separate tool from TypeScript's tsc. Instead, it's built on top of the TypeScript Compiler API. That means it leverages all the core functionality of tsc first—like transpiling TypeScript to JavaScript, enforcing type checking, and respecting your project's TypeScript configuration—then adds Angular-specific compilation steps on top.
2. tsconfig.json is the single source of truth for compilation rules
Since ngc relies on tsc under the hood, it naturally uses tsconfig.json as its primary configuration file. This file isn't just for TypeScript settings either: Angular extends it with an optional angularCompilerOptions section where you can define AOT-specific rules (like enabling strict template type checking, controlling metadata emission, or setting output paths for factory files).
When you run ngc, it:
- Reads your
tsconfig.jsonto get TypeScript settings (liketarget,module,include/excludepaths) - Applies any Angular-specific options from
angularCompilerOptions - Runs the standard TypeScript compilation first
- Then performs Angular's extra steps, like generating
.ngfactory.jsfiles (these are pre-compiled template factories that enable AOT's performance benefits)
3. The unified configuration keeps things simple
Using a single tsconfig.json file means you don't have to maintain separate configs for TypeScript and Angular compilation. This ensures consistency across your project—for example, if you set target: ES2020, both tsc and ngc will emit JavaScript compatible with that version, avoiding mismatches in your output.
To put it plainly: ngc is tsc with superpowers for Angular. It uses tsconfig.json because that's the standard way to configure TypeScript compilation, and it builds on that foundation to handle Angular's unique needs like template compilation and metadata generation.
内容的提问来源于stack exchange,提问作者Unknown developer

