On this page

Migrating from ng build

You have an app that ng build builds from angular.json, with the @angular/build:application builder, and you want to know whether it can move to Vite with this plugin. Most of angular.json's build options become Vite config you'd write for any Vite app. Three have no Vite equivalent, so the plugin takes them, under the same names and in the same shapes: fileReplacements, budgets and polyfills. The project's i18n block and the localize option become the plugin's i18n option. A handful of options can't move at all yet. ng serve's options become Vite's server options, and the scripts in package.json call Vite and Vitest. Then there's your code: ng build compiles the app as one program and Vite one file at a time, and a few patterns only the first can compile.

Read in this order:

  1. Can't move yet, at the end of this page. If your production build depends on anything there, stay on ng build for now.
  2. Getting started, for the toolchain, the Angular version and index.html. Its last step has vite serving your app. Come back here after it.
  3. The rest of this page, top to bottom: the build options, ng serve and the scripts, then what your sources may need if the app compiles but won't load.

If the app lives in an Nx workspace, Migrating inside an Nx workspace adds what the workspace needs: Vite's root, tsconfig paths and the libraries the app imports.

Configurations become modes#

angular.json picks options per configuration, production and development. Vite has modes: vite build runs in production, the dev server in development, and --mode picks another. Write your config as a function of mode to get the same effect:

import {defineConfig} from 'vite';
import {ngp} from '@push-based/vite-plugin-ngp';

export default defineConfig(({mode}) => ({
  plugins: [
    ngp({
      polyfills: ['zone.js'],
      fileReplacements:
        mode === 'production' ? [{replace: 'src/environments/environment.ts', with: 'src/environments/environment.prod.ts'}] : [],
      budgets: [
        {type: 'initial', maximumWarning: '500kB', maximumError: '1MB'},
        {type: 'anyComponentStyle', maximumWarning: '4kB', maximumError: '8kB'},
      ],
    }),
  ],
}));

The plugin doesn't read angular.json. Copy the options over, and delete angular.json once nothing else needs it.

File replacements#

fileReplacements takes angular.json's array unchanged. Paths are relative to Vite's root, which is your project root if index.html sits there.

Vite alone can't do this for an Angular app. ngp's analyzer reads your sources from disk, following imports, so if only Vite swapped environment.ts for environment.prod.ts, the analyzer would still read environment.ts. Any decorator that reads a value from that file, like a template or a providers list built from an environment constant, would compile against the development file. The plugin gives both Vite and the analyzer the replacement's content, under the replaced file's name. The plugin's tests cover this with a component whose template comes from the environment file.

Two things differ from the CLI:

  • The replacement's relative imports resolve from the replaced file's directory. If environment.prod.ts sits next to environment.ts, as it does in every CLI project, nothing changes. A replacement in another directory whose relative imports expect its own location would resolve them from the wrong place.
  • Errors and source maps name the replaced file, environment.ts, even though its code is the replacement's.

In the dev server, an edit to the replacement reloads the page with the new content. An edit to the replaced file does nothing while the replacement applies.

For code you write from now on, consider Vite's own env variables instead. import.meta.env.PROD and .env.production files need no replacement at all.

Budgets#

budgets takes angular.json's array unchanged: every type (initial, all, allScript, any, anyScript, bundle, anyComponentStyle) and every threshold (maximumWarning, maximumError, minimumWarning, minimumError, warning, error, baseline). After vite build, failures print in the CLI's words:

▲ [WARNING] bundle initial exceeded maximum budget. Budget 500.00 kB was not met by 6.26 kB with a total of 506.26 kB.

A warning leaves the build passing. An error fails it, after every failure has been printed, so CI scripts that check the exit code or grep for these lines keep working.

Sizes are of the files on disk, before compression, as with the CLI. Only the browser build is checked, and only .js and .css files count. Three things differ:

  • Inline styles are measured as written. anyComponentStyle measures a styleUrl file as ng build does: compiled, then minified, before view encapsulation rewrites its selectors. In the repo's playground, app.css is 4,282 bytes as written and measures 3,339. Inline styles are different: ngp compiles them and ships them as written, so that's what they're measured at, and a long inline style can trip a budget that ng build wouldn't.
  • Bundle names are Vite's. A bundle budget matches a chunk by its Rolldown name. Lazy chunks are named after their file, like feature-detail. The chunk holding src/main.ts also answers to main. Polyfills go into the entry chunk, so a bundle budget named polyfills measures nothing.
  • Initial means what index.html loads before your app runs: the entry chunk, the chunks it imports statically, and their CSS. That's the CLI's meaning too, but Vite splits chunks differently, so expect a different total for the same app.

Polyfills and zone.js#

polyfills takes angular.json's array: package names like zone.js, or files in your project like src/polyfills.ts. The plugin imports them at the top of each entry module, so they run before Angular does, in the dev server, in the build and on the server.

A zoneless app, which is what ng new creates since Angular 21, needs nothing here. If your app still calls provideZoneChangeDetection(), list zone.js, and the plugin does what the CLI does:

  • On the server, zone.js becomes zone.js/node. The server gets no other polyfills, except @angular/localize/init.
  • async and await are rewritten into generators. zone.js can't see a native await, so the code after one runs outside Angular's zone and change detection never runs for it. In the plugin's test app, a component that sets a field after an await stays on "loading" forever without the rewrite. The CLI turns off esbuild's async-await support for zone.js apps, and the plugin uses esbuild with the same setting, on your code and on your dependencies. It costs little: 452 bytes and about 60 ms per build, on a 311 kB test app.

The plugin decides your app uses zone.js the way the CLI does: zone.js is in polyfills, or any polyfill is a file, since a file might import it.

One thing catches zone.js apps out on any build tool: in Angular 22.3, components are OnPush unless they say otherwise. A component that relies on zone.js to re-render after a plain field changes needs changeDetection: ChangeDetectionStrategy.Eager.

Under Vitest, the plugin imports no polyfills, because specs have no entry module, but it still rewrites async functions. A zone.js test setup imports zone.js and zone.js/testing in its setup file. See Testing with Vitest.

Where every option goes#

Every option of @angular/build:application, as of Angular 22.3:

angular.jsonWith Vite and the plugin
browserThe <script type="module" src="/src/main.ts"> in index.html. Set the plugin's entries if it isn't src/main.ts
indexindex.html in Vite's root, usually your project root. The output is always index.html
tsConfigThe plugin's tsconfig. It defaults to tsconfig.app.json
polyfillsThe plugin's polyfills
fileReplacementsThe plugin's fileReplacements
budgetsThe plugin's budgets
assetsVite's public/ directory, which is what ng new's default {"glob": "**/*", "input": "public"} copies. Other globs need a copy plugin
stylesimport './styles.css' in main.ts, or a <link rel="stylesheet" href="/src/styles.css"> in index.html. Vite compiles .scss once sass is installed
scriptsPut them in public/ and add a plain <script src> to index.html. Vite leaves classic scripts as they are
baseHrefVite's base, plus <base href="%BASE_URL%"> in index.html. Vite fills in %BASE_URL% from base
deployUrlVite's base, or experimental.renderBuiltUrl for a CDN. The CLI deprecated it
defineVite's define, in the same format: each value is a string of code
sourceMapbuild.sourcemap: true, or 'hidden' for hidden. Vite has no separate switch for vendor or style maps
optimizationOn by default in vite build: Rolldown minifies, and the plugin runs the CLI's build optimizer. styles.inlineCritical and fonts.inline have no equivalent
outputHashingVite hashes every file name by default. build.rolldownOptions.output changes the patterns
outputPathbuild.outDir. With the plugin's ssr, output goes to <outDir>/client and <outDir>/server
deleteOutputPathbuild.emptyOutDir
extractLicensesbuild.license, which writes .vite/license.md instead of 3rdpartylicenses.txt
namedChunksVite names chunks after their file by default
externalDependenciesbuild.rolldownOptions.external
allowedCommonJsDependenciesNothing: Vite doesn't warn about CommonJS dependencies
loaderVite's ?raw and ?url import suffixes, and assetsInclude
conditionsresolve.conditions
preserveSymlinksresolve.preserveSymlinks
server, ssrThe plugin's ssr option. See Server rendering
aotAlways on. The plugin has no JIT mode
watch, pollThe dev server watches by default. server.watch.usePolling for polling
progress, verbose, clearScreenVite's logLevel and clearScreen
crossOriginVite adds crossorigin to the module scripts it injects
webWorkerTsConfigVite's new Worker(new URL('./app.worker.ts', import.meta.url), {type: 'module'}). Untested with the plugin
statsJsonNo equivalent. build.manifest lists the chunks; a bundle visualizer plugin shows their contents
stylePreprocessorOptionsVite's css.preprocessorOptions, for example scss: {loadPaths: ['src/styles']}. styleUrl files go through Vite's CSS pipeline. See Component styles
inlineStyleLanguageNot supported: inline styles are plain CSS, because ngp compiles them. Move preprocessed styles to a styleUrl file
localize, i18nMissingTranslationThe plugin's i18n option: locales names the locales to build, missingTranslation replaces i18nMissingTranslation. See Internationalization
i18nDuplicateTranslationNo equivalent. A message id that appears twice in one translation file is an error. When a locale has several files, the last file's translation wins, with no warning
server, ssr, prerender, outputModeWith @angular/ssr, ssr: true in the plugin. It finds src/main.server.ts and src/server.ts by name, and vite build prerenders what your server routes ask for, as outputMode: 'server' does. Change browserDistFolder in server.ts to ../client. See Server rendering
security.allowedHostsssr: {allowedHosts: [...]}
appShellNot supported
serviceWorkerNot supported. ngsw-config from @angular/service-worker can generate the manifest from the built output, but that's untested here
subresourceIntegrityNot supported
security (autoCsp)Not supported

The CLI also reads .browserslistrc for its syntax target. Vite doesn't: set build.target yourself if you support older browsers than Vite's default, which is the "widely available" Baseline.

Moving ng serve#

ng serve runs @angular/build:dev-server with the options under the serve target in angular.json. That builder runs Vite too, so most of its options are a Vite option under another name. Vite's dev server reads them from server in vite.config.ts, and vite preview, which serves what vite build wrote, from preview. The names below are from the dev-server builder's schema in @angular/build 22.3.0 and Vite 8.3's types:

angular.json serveWith Vite and the plugin
buildTargetNothing. The dev server and vite build read the same vite.config.ts, and --configuration becomes --mode
portserver.port, or vite --port. The CLI's default is 4200, Vite's 5173, and Vite doesn't read the PORT variable. When the port is taken Vite tries the next one; server.strictPort: true makes it exit instead
hostserver.host, or vite --host. true or '0.0.0.0' listens on every address, your LAN included
proxyConfigserver.proxy, and preview.proxy for vite preview. See the proxy
ssl, sslKey, sslCertserver.https: {key, cert}, with each file's contents from fs.readFileSync. With ssl and no files, the CLI makes a certificate with @vitejs/plugin-basic-ssl; add that plugin to your config to do the same
headersserver.headers
openserver.open, or vite --open
allowedHostsserver.allowedHosts. The CLI hands it to Vite under the same name
defineVite's define. It applies to vite build too, so pick the values by mode if they're for the dev server only
servePathVite's base
hmrThe plugin's hmr option. hmr: false makes every edit reload the page, as it does under ng serve
liveReloadliveReload: false, which turns hmr off too unless you set it, means no updates and no reloads. That's Vite's server.hmr: false: Vite then sends nothing when a file changes. server.ws: false also closes the WebSocket, as the CLI does
watch, pollserver.watch: null stops watching. poll: 500 is server.watch: {usePolling: true, interval: 500}
verboseVite's logLevel, or vite --debug
inspectvite --profile starts Node's inspector
prebundleVite's optimizeDeps: prebundle: {exclude: [...]} is optimizeDeps.exclude. Untested with the plugin

The proxy#

The CLI's dev server passes your proxy file to Vite, so an entry in the object form moves over as it is:

vite.config.ts
const proxy = {'/api': {target: 'http://localhost:3000', secure: false}};

export default defineConfig({
  server: {proxy},
  preview: {proxy},
  plugins: [ngp()],
});

Before it hands the file over, the CLI converts three things that Vite doesn't accept, so write those yourself:

  • A key with a glob, like /api/**. Vite matches a key as a prefix of the URL, or as a regular expression when it starts with ^. /api/** becomes /api.
  • The array form, with context: ['/api', '/auth']. Write one key per entry in context.
  • pathRewrite: {"^/api": ""}. Vite's option is a function: rewrite: (path) => path.replace(/^\/api/, '').

The bench's config for Ghostfolio does this for the paths its proxy.conf.json sends to the API, in server.proxy and preview.proxy. It's in the repo, at bench/real/ghostfolio/vite.config.ngp.mjs.

Scripts, index.html and tests#

The scripts in package.json call Vite and Vitest instead of ng:

package.json
{
  "scripts": {
    "start": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "test": "vitest run"
  }
}

vitest on its own watches and reruns in a terminal. vitest run runs once, which is what CI wants and what the create-ngp templates write. ng build --configuration development becomes vite build --mode development, with your config picking options by mode. ng extract-i18n becomes the plugin's ngp-extract-i18n, and ng generate its ngp-generate.

The CLI's index.html sits in src/ and has no script tag: ng build adds the script and style tags. Vite's sits in Vite's root, your project root, and has to load the app. Move it up out of src/ and add <script type="module" src="/src/main.ts"></script> at the end of <body>. Getting started has the whole file. Keep <base href="/">. Global styles go in with an import or a <link>, as the table above says under styles.

The test target is @angular/build:unit-test in a recent app, which runs Vitest, or Karma in an older one. Neither reads your vite.config.ts. With the plugin you run Vitest yourself, from a vitest.config.ts with ngp() in its plugins and a setup file that starts TestBed. Testing with Vitest has the setup, which DOM to pick, and the switches for specs written for Karma's JIT compile.

What your sources may need#

ng build compiles your app as one TypeScript program, so it knows every file's types when it writes any of them. Vite compiles one file at a time, and so does ngp. A little code depends on the whole program, and nothing in angular.json warns you about it. These are the problems found moving two real apps, Super Productivity, an Angular CLI app with 252 components, and Ghostfolio, an Nx workspace with 157. Each app's fixes are a patch in bench/real/, with a header saying why, and both ng build and the plugin compile the patched sources. Fix your sources the same way, so you can keep comparing the two while you move.

Type-only re-exports#

What you see. The page stays blank, and the browser console says a module doesn't provide an export, named after an interface. vite build stops with "missing export".

Why. export {SomeInterface} from './x' names a type, but a file compiled on its own can't tell: SomeInterface is declared in another file. So the statement stays in the output as a runtime re-export of a value x never exports. ng build drops it, because it has the whole program's types.

Fix. Write export type {SomeInterface} from './x', or export {type SomeInterface, someValue} from './x' when the statement mixes types and values. To find them all, set isolatedModules: true in your tsconfig, as ng new has since Angular 19. TypeScript then reports each one as TS1205, and its quick fix writes the type. Super Productivity had 7 such statements in 5 files, and Ghostfolio 1, in libs/common. The bench applied TypeScript's quick fix to each with a script you can run on your own app.

Decorator metadata#

What you see. A module with a decorated class fails to load, with the same missing-export error, naming the type of a decorated member's parameter. Super Productivity hit it on its first page, in its own @debounce() method decorators.

Why. emitDecoratorMetadata: true writes each decorated member's parameter types into the output as design:paramtypes, which are values at runtime. Vite's per-file transform honours the option, and for a parameter typed with an interface from another file it can't tell that the name isn't a class, so it imports it as a value. The import finds nothing. ng build has the whole program and writes Object there. Angular stopped needing decorator metadata years ago, but older tsconfigs still turn it on: both apps did, and Nx writes it into tsconfig.base.json.

Fix. Turn it off for Vite. Both apps' configs do this:

vite.config.ts
export default defineConfig({
  oxc: {decorator: {legacy: true, emitDecoratorMetadata: false}},
  plugins: [ngp()],
});

Deleting emitDecoratorMetadata from your tsconfig works too, unless something else compiled from it needs the metadata; a NestJS API does. With isolatedModules on, TypeScript reports each import this would break as TS1272.

TypeScript transformers#

What you see. Code a transformer should have rewritten at compile time runs as you wrote it. With typia, the first typia.createAssert() throws when the app starts.

Why. Some libraries work at compile time. typia's typia.assert<T>() is a placeholder that a TypeScript transformer replaces with a validator generated from T. The transformer is listed in your tsconfig's compilerOptions.plugins, as an entry with transform, and ts-patch makes the CLI's TypeScript run it. Neither Vite nor ngp runs TypeScript transformers.

Fix. A Vite plugin, placed before ngp(), that runs the transformer on each file that needs it. For typia, unplugin-typia does that; it hasn't been tried with this plugin. The bench wrote its own for Super Productivity, bench/real/super-productivity/bench-typia.mjs: it builds a TypeScript program over the app, runs typia's transformer on each module that mentions typia, and prints TypeScript back out for ngp to compile. The transformer needs the type checker, so either way something builds the whole program, and that took a few seconds of each dev-server start and each build on Super Productivity. Look for transform in your tsconfig's plugins before you start.

TypeScript 7 is stricter#

What you see. Type errors in code ng build accepts: in the terminal and Vite's overlay in the dev server, and a failed vite build.

Why. ng build checks types with TypeScript 6, which Angular 22.3 needs. ngp doesn't check types at all, so the plugin runs its own type-check with TypeScript 7, against your tsconfig, and TypeScript 7 infers some types differently. In Super Productivity's date picker it inferred cal.activeDate as unknown where TypeScript 6 inferred Date, and reported TS18046 and TS2769. It also refuses a tsconfig paths target that doesn't start with ./ when there's no baseUrl, with TS5090.

Fix. Make the code say what TypeScript 6 inferred. Two as Date casts fixed Super Productivity, and they change nothing at runtime. Start paths targets with ./. To move first and fix later, typeCheck: false turns the check off; until you turn it back on, nothing in Vite checks your types or templates, and vite build passes with errors.

Template errors ngc doesn't report#

What you see. A type error in a template that ng build accepts, at the template's line and column.

Why. The check runs TypeScript over a type-check block per component, code that calls every template expression against the component's types, and ngp writes those blocks itself. They aren't the same as ngc's. In Ghostfolio, @if (tab.onClick), where tab is a union of a tab with onClick and a tab with routerLink, gets TS2774 ("This condition will always return true since this function is always defined") from ngp's blocks, and nothing from ngc's. Which one is right is a question for the two compilers.

Fix. If your code is right, take the expression out of the check with Angular's $any(): @if ($any(tab).onClick). It changes nothing at runtime. Ghostfolio needed it on two expressions in one template. If you think ngp is wrong, open a bug report with the template: output that differs from ng build is a bug here, even when the cause is in ngp.

Can't move yet#

If your production build relies on any of these, it can't move to the plugin today:

  • @angular/ssr with i18n, or the app shell. @angular/ssr itself works, render modes and prerendering included, for one locale (Server rendering).
  • Sass, Less or other preprocessors in inline styles. styleUrl files and global styles are fine: Vite compiles those.
  • The service worker. @angular/service-worker's manifest isn't generated.
  • Critical CSS inlining, subresource integrity and autoCsp.
  • A library project. ng build my-lib runs ng-packagr, and the plugin doesn't replace it: it compiles apps, and a library an app imports compiles with the app. Keep ng-packagr for a library you publish. See Buildable and publishable libraries.

Status and limits has the full list of what the plugin doesn't do yet, beyond build options.