On this page
- Why per-module compilation was impossible before
- Compiling one module
- Handling an edit
- Keeping edits cheap in large apps
- Component HMR
- Component stylesheets
- Type-checking
- Linking libraries
- Compile-time globals
- Build options from angular.json
- The build optimizer
- Reusing output between builds
- Sharing one directory between projects
How it works
Every dev server built on Angular's compiler compiles your whole program before it serves a single module. vite-plugin-ngp compiles each file when Vite asks for it, and only that file. This page explains how, for anyone who wants to know what the plugin does before trusting it with an app.
Why per-module compilation was impossible before#
ngc, the compiler behind ng serve and ng build, can't compile one file until it has built a TypeScript program of the whole project and analyzed every decorator in it. So every tool built on ngc works around Vite instead of with it. ng serve runs esbuild and uses Vite only to serve the output. @analogjs/vite-plugin-angular compiles the program up front and ignores the code Vite passes to its transform. Compared with alternatives puts the two next to Analog's per-file fastCompile and @oxc-angular/vite.
ngp, which Angular merged on 8 October 2026, splits the compiler in two. A Rust analyzer, built on oxc, reads decorators and resolves references across files, and it answers per file, on demand. Angular's existing template compiler, in TypeScript, then generates the code. For each file ngp returns plain TypeScript with the decorators compiled away, which is exactly what a Vite transform should return.
Compiling one module#
When the browser asks for a .ts file, Vite hands its code to the plugin's transform hook. The plugin runs before Vite's own TypeScript transform, and it:
- Tells the analyzer about the code, if it differs from what the analyzer last saw. Another plugin may have changed it on the way. Code Vite read before your latest save is left out, as the next section explains.
- Calls ngp's
processFilefor that one file, in optimize mode. - Returns ngp's TypeScript and a source map. Vite's transform then strips the types, as it does for any TypeScript file.
Files without Angular decorators come back unchanged. One compiler lives as long as the dev server, so nothing is analyzed twice.
The plugin always uses ngp's optimize mode, in development and in production. ngp's other mode, local, compiled 745 of 1,089 modules differently when they were compiled one at a time: components lost ChangeDetectionStrategy.OnPush, which changes how an app behaves at runtime. Optimize mode matched a full build for every module.
Handling an edit#
When a file changes, the plugin sends the new content to the analyzer. The analyzer answers with every file whose output may have changed. The plugin drops those files from ngp's cache and invalidates them in Vite's module graph. Vite then asks again for the ones the page still uses.
Adding, renaming and deleting files works the same way. The analyzer finds a new file through the import that adds it. When you delete a file, the plugin tells the analyzer it's gone and recompiles everything that imports it. An importer that still uses the file fails with an error, and recovers when the file is back. If a component's templateUrl points at a file that doesn't exist, the plugin reports NG2008: Could not find template file, as ng build would. ngp on its own would compile it to an empty template.
The Angular CLI's path runs a "delta" pass after each edit, which streams every file in the program again: 465 ms at 5,000 components. The plugin skips it, because Vite's module graph already knows which modules the page still uses.
A transform can carry code from before a save: Vite read the module, you saved, and only then did the transform run. Sending that code to the analyzer would undo your save for every component compiled before the file's next transform. So the plugin notes when Vite read each module, and a transform of a module read before the latest edit leaves the analyzer alone, unless its code is what's on disk now. Vite throws that transform's result away anyway, because your save invalidated the module while it ran, and compiles it again.
Keeping edits cheap in large apps#
After every update, ngp's analyzer reloads its tsconfig and walks the whole source tree to re-expand the include globs. At 5,000 components that made a one-line edit cost 172 ms. So the plugin gives the analyzer a generated tsconfig that extends yours and lists only the entry points. The analyzer finds every other file by following imports, and the same edit costs about 1 ms, with identical output. Turn this off with entryOnlyTsconfig: false.
Component HMR#
In the dev server, ngp compiles each component with the same HMR code the Angular CLI's compiler adds. When you edit a component's external template, or only the inline template or styles in its .ts file:
- The plugin asks ngp for that component's update module, strips its types, and stores it.
- It sends
angular:component-updateover Vite's HMR channel. - Angular's runtime fetches the update from
/@ng/component?c=<id>, which the plugin serves, and swaps the new template into the running component.
The component keeps its state: a counter at 2 stays at 2 while its heading changes. If the runtime can't apply an update, it says so, and the plugin reloads the page.
The <id> is the component's file and class name, the way Angular's compiler writes it into the compiled component: the path from the folder that holds your tsconfig for a file inside it, and the file's full path for one outside, like libs/ui next to apps/landing in a monorepo. With workspaceRoot it's the path from the workspace root for both. Either way both update in place. Vite only watches its root, and a file outside it once Vite loads it as a module. ngp reads templates itself, so Vite never loads them: the plugin adds each component's templateUrl file outside the root to Vite's watcher when it compiles the component. Before 4 December 2026 it didn't, and an edit to a library's template did nothing until your config added the folder with server.watcher.add().
For a .ts edit, the plugin decides with the same rules as the Angular CLI's dev server. It compares the file before and after the edit, as text. If the only difference is inside the template or styles value of a component's decorator, those components update in place. In a file with several components, only the ones you edited update. Any other difference reloads the page: a new entry in imports, a changed selector, an input, a method, an import or a constant at the top of the file. An update can't bring in code the running page doesn't have yet, so those need the reload.
The comparison is strict, and that's deliberate. It doesn't try to tell a harmless change from a real one, so reformatting a method reloads too. Two cases update in place under ng serve and reload here: a template kept in a constant outside the decorator, which is a top-level change, and an edit to templateUrl or styleUrl.
If one save changes both a component's template and its .ts file, and the .ts change needs a reload, the page reloads once, without trying the template update first. The new template may use a field the running class doesn't have yet. If the .ts change only touched inline templates or styles, both update in place. The plugin holds a template update until 50 ms after the template was written, by its modification time, to see whether the .ts file changed too. On macOS, Vite's watcher usually reports a write about 110 ms after it, so the 50 ms has passed by then and the update goes out at once. When the watcher reports within about 10 ms, the update waits out the remaining 40 ms. It then compares the class the page last loaded with the latest one on disk, so it doesn't matter in which order, or how far apart, the watcher reports the two files.
Component stylesheets#
ngp compiles with externalRuntimeStyles, so it leaves styleUrl files out of the component and lists their paths instead. The plugin hands those files to Vite's CSS pipeline, which runs Sass and PostCSS on them like on any stylesheet, and then applies Angular's view encapsulation to Vite's output with Angular's own code.
In the dev server, each stylesheet is a <link> the runtime adds, and an edit reloads only that <link>, so the component keeps its state. In builds, each stylesheet is compiled, scoped and inlined into the component's JavaScript. Inline styles stay with ngp and can't use Sass. Component styles has the details and the differences from the CLI.
Type-checking#
Compiling a module doesn't check its types. Separately, after startup and after each edit, the plugin asks ngp for a type-check block per component file, and runs TypeScript 7 over your app and those blocks in another process. It maps errors in a block back to your template. Angular's extended diagnostics, the NG81xx template checks, do come out of the compile itself, as warnings. Type-checking has the details.
Linking libraries#
Angular libraries, Angular's own packages included, ship partially compiled: ɵɵngDeclareComponent(...) calls that describe a component without being its runtime code. The linker rewrites them into the final code for your Angular version, as the CLI does. ngp only compiles your own sources, so the plugin runs Angular's linker on every module in node_modules that needs it:
- In development, inside Vite's dependency pre-bundling, which runs outside the normal plugin pipeline. With
ssr, the server's libraries are pre-bundled too, intonode_modules/.vite/deps_ssr; see Server rendering. A server environment another plugin adds, like a Cloudflare Worker's, gets the linker in its own pre-bundling. A library the dev server serves without pre-bundling is linked in the normal transform, under the?v=query Vite adds to its URL. - In production builds and server bundles, in the normal transform. On the server, the plugin bundles every Angular library it finds in your
dependencies, so the linker sees them too. - Under Vitest, in the normal transform. The plugin has Vitest inline every Angular library instead of leaving it to Node, so the linker sees them. With
test.externalLibrariesthey stay with Node, and a Node module hook links each one as it loads, from the same cache entries. See Testing with Vitest.
Without a linker, the browser would need Angular's JIT compiler to finish compiling libraries at startup. In the playground, linking cut the production bundle from 1,197 kB to 589 kB.
The linking is Angular's own FileLinker, from @angular/compiler-cli/linker, but the plugin doesn't run it through Babel. It parses the module once with the oxc parser Vite ships, hands each ɵɵngDeclare call to the linker, and splices the definition it gets back into the original text. The module is never printed, so everything outside those calls comes out byte for byte as it went in. This is the design the Angular CLI moved to in 2026 (angular/angular-cli#33625), ported here because the CLI's copy is private to @angular/build. One visible difference from the Babel linker: each declaration's constants, like its parsed template, stay in a pure IIFE around the definition instead of moving to module scope, so an unused component's constants disappear with it when the bundler drops the component.
It's about three times faster. Linking the 21 partially compiled modules of Angular's own packages in this repo, 626 kB in all, takes the oxc path about 75 ms warm against about 225 ms for Babel, and the first module 36 ms against 298 ms, since there's no Babel to load. That's the two link functions timed in one Node process on a laptop on 9 November 2026, not a bench run; the Performance page's cold-start figures were measured before the change.
Compile-time globals#
The plugin defines the same globals the Angular CLI does, so the minifier can drop code your build doesn't need:
| Global | Value |
|---|---|
ngJitMode | false everywhere, since the linker makes every library ahead-of-time compiled. true under Vitest with test.jitCompat |
ngDevMode | false in builds |
ngServerMode | false in the browser, true in server environments |
ngHmrMode | true in the dev server's browser environment, false in builds, server environments, under Vitest and with hmr: false |
ngI18nClosureMode | false everywhere, so i18n messages compile to $localize calls, never Closure's goog.getMsg |
Under Vitest with test.externalLibraries, Angular's libraries don't go through Vite, so ngJitMode and ngServerMode are set on globalThis for them, to the same values.
These took the playground's bundle from 589 kB to 386 kB, and stopped production builds from logging "Angular is running in development mode".
Build options from angular.json#
Three angular.json options need the plugin, not just Vite. The migration guide says how to use them. This is what they do inside.
File replacements reach the analyzer. ngp's analyzer reads files from disk by following imports, so it would never see a replacement that only Vite knows about. When the plugin starts a compiler, it sends the analyzer each replacement's content under the replaced file's path, before anything compiles. Vite's load hook returns the same content for the same path. Both see one file, with the replacement's code, so a component whose template comes from environment.ts compiles with the production template. The analyzer only learns about the replacement from the plugin: from the watcher when you edit it, never from a transform, which can carry code read just before your edit.
Polyfills are the entry's first imports. The plugin puts one import per polyfill at the top of src/main.ts and of your server entry. On the server, zone.js becomes zone.js/node. With @angular/ssr, the server build has two entries, main.server.js and server.js, which share a chunk with Angular in it, and zone.js/node is the first import of each, ahead of that chunk.
zone.js apps get their async functions rewritten. Code after a native await runs outside zone.js's view, so Angular never runs change detection for it. Like the CLI, the plugin rewrites async functions into generators with esbuild for zone.js apps, and leaves every other modern feature alone. Builds rewrite each output chunk once. The dev server rewrites each module that contains async as it serves it, dependencies included.
The build optimizer#
vite build runs one more pass over your code and your libraries, which the dev server skips: Angular's build optimizer, the same rewrites ng build makes. Despite the name, it has nothing to do with ngp's optimize mode. It exists because the bundler can only drop code it knows is safe to drop, and Angular's compiled output doesn't say which code that is. A component's static ɵcmp = ɵɵdefineComponent(...) is a function call, so without help Rolldown keeps every component, pipe and service it has seen, whether your app uses it or not.
The plugin's pass is a port of the CLI's, and makes the same changes:
- A class with Angular's static definitions (
ɵcmp,ɵfac,ɵprovand the rest) moves into a function marked/*#__PURE__*/. If nothing uses the class, Rolldown drops it with its definition. - In Angular's own packages, which declare
"sideEffects": false, every top-level call andnewis marked pure. In your code and in other libraries, onlynew InjectionToken(...)is. - TypeScript enums move into a pure function too, and
forwardRef(...)calls count as pure. ɵsetClassMetadatacalls and JIT-only decorator metadata are removed. WithngDevModeset tofalsethe minifier drops those anyway, so this changes nothing you'd notice.
Measured on the repo's playground, with the same script for each build (raw size, gzip in brackets):
| JavaScript on the first page | All JavaScript | |
|---|---|---|
| Before the optimizer | 502 kB (158 kB) | 552 kB (179 kB) |
| With it | 316 kB (99 kB) | 390 kB (129 kB) |
ng build of the same app | 336 kB (109 kB) | 383 kB (129 kB) |
On this site, the first page's JavaScript went from 462 kB to 298 kB (143 kB to 93 kB gzipped). Taken as a whole, the plugin's output is now as big as ng build's for the same app: 2% larger raw, the same size gzipped. The first page is smaller than ng build's only because Rolldown splits chunks differently from esbuild.
The pass trusts what the CLI trusts: that no top-level code in Angular's packages runs for its side effects. And it's a copy, so when the CLI changes its pass, the plugin's stays as it was until someone ports the change.
Reusing output between builds#
Building the 5,000-component app spends most of its time transforming modules: 14.6 of 16.6 seconds without type-checking, and most of that is ngp's code generation, which is Angular's template compiler in TypeScript (Performance). Every build paid it in full, and in an Nx workspace every app build paid it again for every library file.
Since 9 November 2026, vite build and Vitest keep what they compiled, under Vite's cacheDir, at node_modules/.vite/vite-plugin-ngp/cache by default, or in the directory cache: {dir} names. Three things are kept, one entry per module, each named by a hash of what its output depends on:
- ngp's output for one of your modules. The hash covers the ngp build (every
.jsfile of its preprocessor, so a patched or rebuilt one misses), the plugin's own code, the Angular compiler's version, the folder ngp writes paths from (your tsconfig's, orworkspaceRoot) and every compiler option except the few that only say where the tsconfig is and wheretscwould write; the module's path and its code as Vite hands it over; the content of its external templates and stylesheets; and the analyzer's metadata for the file. That metadata carries the selector, inputs, outputs, standalone flag and host directives of every component, directive and pipe the module's templates use, and the value of every constant its decorators read. So adding an input to a child component recompiles its parents, and editing a comment in the child's file doesn't. - The linker's output for a library module in
node_modules, by the file and its content. - The build optimizer's output, by the module's code and its package's
sideEffectssetting.
The analyzer runs on every build either way, because the hash needs its metadata. That's the Rust part, and the cheap one. What a hit skips is the TypeScript code generation, the build optimizer and, for libraries, the linker. Diagnostics are kept with the output, so a warning repeats on a hit as it would on a compile. A missing template file is never cached, since that compile has to report NG2008.
The dev server doesn't use the cache. It compiles only what the page asks for, and a restart on the 5,000-component app already paints in 0.57 seconds, most of it Vite's own dependency pre-bundling, which Vite caches itself.
What it saves, measured on 9 November 2026 on an M4 Max laptop that was running other work at the time, so the cold figures are two to three times the Performance page's and vary by up to 40% between runs. Each row is the median of 3 builds in one session, cold with the cache deleted first, warm straight after, so only the two columns of one row compare. They were taken with the Babel linker the plugin used until that day, so the cold column includes it:
| App | Cold | Warm, nothing changed |
|---|---|---|
1,000 components, typeCheck: false | 6.1 s | 2.4 s |
5,000 components, typeCheck: false | 48 s | 16 s |
| 5,000 components, type-checked | 82 s | 55 s |
| playground, with SSR, i18n and type-checking | 3.7 s | 2.1 s |
On the 5,000-component app a warm build after one template edit took as long as a warm build with nothing changed, 57 s against 55, which is inside the run-to-run noise: one module compiles and the rest hit. The type-check doesn't shrink, because it checks the whole program every time, so a type-checked warm build is bounded by it. The cache is big: 50 MB for the 1,000-component app and 219 MB for 5,000, most of it source maps, and nothing prunes it. These numbers weren't taken with the bench harness; the Performance page's will be, in a later rerun.
To see what a build reused, set DEBUG=vite-plugin-ngp: each module is logged as compiled, reused or unchanged, and the build ends with the hit and miss count. cache: false turns it off (Configuration).
Where it's weak: a hash with a missing input would serve a wrong module with no error. The repo has a test for each kind of input, from a template edit to a new input on a used component, and the metadata the key hashes is the analyzer's whole result for the file, with only its run-specific ids and spans removed. If a build ever comes out stale, cache: false is the check, and the key is the bug.
Sharing one directory between projects#
Under Vitest, a project's cacheDir is vitest/<hash of the project's name> inside Vite's cacheDir, which is node_modules/.vite under the project's own root unless you set it. So every project has its own output cache. In a workspace with hundreds of Vitest projects, each one links @angular/common and every other Angular library for itself. Vitest's own module cache doesn't help either: its key holds the project's root and the content of its config files, so one project never reads what another transformed.
Since 26 November 2026, cache: {dir: 'path'} names the output cache's directory, absolute or relative to Vite's root (Configuration). Point every project at the same one, and when Vitest asks for a library a project hasn't seen, the plugin reads what another project linked instead of linking it again.
Only the directory changes. Every entry keeps the key it had:
- Library code is shared. The linker's key is the file's path, its content and whether
test.jitCompatis on, under the plugin's own code and the installed Angular versions. Nothing in it names a project, so two projects that resolve the same file read the same entry. The same goes for the build optimizer's output for a library module. - Your compiled modules are not, by default. ngp writes paths into a compiled module from the folder that holds the project's tsconfig: the file in a class's debug info, and in a component's HMR id. So that folder is in the key, and a library file two projects import is compiled once for each. A test in the repo runs two projects with different roots on one directory, as builds and as Vitest runs: the second reads the first one's libraries, and none of its compiled modules.
- With
workspaceRoot, they are. Since 26 November 2026 theworkspaceRootoption makes ngp write those paths from the workspace root, the same in every project. The key then holds that folder, and the compiler options without the ones that only say where a tsconfig is and wheretscwould write (configFilePath,basePath,genDir,outDir,declarationDir,tsBuildInfoFile,rootDir). Two projects with the same options otherwise read each other's compiled modules. Every other option stays in the key, the template checks among them, because an entry holds the module's diagnostics too: a project withstrictTemplatesand one without never share. The analyzer's metadata stays in the key as well, so two projects that resolve one of the module's imports differently miss. Another test runs two projects that import one library file: withworkspaceRootthe second runs the module the first compiled, and without it, or with different template checks, it compiles its own.
Many projects can write at once. Each entry is written to a temporary file and renamed into place, and the temporary name is unique to the process and to the cache, so two plugins in one Vitest process can't pick the same one.
What it saves, on an M4 Max on 26 November 2026: three specs of the plugin's own Vitest fixture, which link 16 library modules into 346 kB of code, five runs of each case, with Vitest's module cache empty for the project.
| A project Vitest has never run | Run time |
|---|---|
| Empty directory, so it links everything | 1.20–1.29 s |
| Directory another project filled | 1.09–1.15 s |
| For comparison: the same project again, Vitest's own cache warm | 0.48–0.49 s |
| The same project with only Vitest's cache emptied, 4 runs | 1.06–1.10 s |
Where it's weak: that's about 0.1 s of the roughly 0.75 s a project's first run costs over its second. Linking isn't most of it. The last row shows where the rest goes: with everything the plugin keeps still in place, the project's own compiled modules too, emptying Vitest's cache alone costs about 0.6 s. That's Vitest's own work on every inlined library, @angular/core included, which never needs linking, and Vitest keeps the result per project. The plugin can't share that part. It can keep the libraries away from Vitest, though: with test.externalLibraries Node loads them and a hook links them from this same directory, and a project Vitest has never run then took 0.34–0.39 s on the same fixture. What sharing compiled modules saves wasn't measured: the fixture has one shared component, and compiling cost 2–20 ms a module in the playground. Projects whose template checks differ still compile for themselves; reporting a module's diagnostics apart from its code would lift that, and is open in issue #61. The analyzer still reads every file a run reaches, in every project. The directory only works within one checkout on one machine, since keys hold absolute paths. Nothing prunes it, and now every project adds to it. Its entries are code your builds and tests run, so whoever can write to the directory can change that code: keep it where only your own builds write, as you do node_modules. And when many projects start cold at once, each links the same libraries before any has written them: wasted work, not wrong output.
Together, cache.dir, workspaceRoot and test.externalLibraries are meant to do what a Vitest module cache shared between projects would do, without one. They don't cover all of it, and none of this has run on a workspace with hundreds of projects:
- Projects whose template checks differ compile your libraries separately. They share within a group that has the same compiler options, not across groups.
- Your own non-Angular TypeScript is still transformed once per project, by Vite, and cached by Vitest per project. ngp never sees those files.
- The analyzer reads every file a run reaches in every project. Only the code generation is shared.
test.externalLibrarieschanges whatvi.mockreaches and needs poolforksorthreads(Libraries left to Node).- One checkout on one machine. A cache filled on CI isn't read on a laptop that checked the repo out somewhere else.