Sub topic 14
Building for production
This chapter turns the task list app into files you can put on a web server. It covers what ng build does, how to read its output, how to keep the bundle small, and why routes like /tasks/3 break on a plain file server. It assumes you finished the earlier chapters: you have the task-list project, the router with tasks/:id, and TaskApi calling /api/tasks. You should also be comfortable with a terminal and with JSON files such as angular.json.
What `ng build` does
ng serve keeps the app in memory and rebuilds it on every change. It is for development only. ng build compiles the app once and writes static files to disk.
ng buildIn projects created with Angular 17 or later, ng build uses the production configuration by default. It does the following:
- Compiles templates ahead of time, so the browser never needs the Angular compiler.
- Bundles and minifies the TypeScript and CSS.
- Removes unused code ("tree shaking"). Imports you never use do not reach the output.
- Splits lazy-loaded routes into separate chunks.
- Adds a content hash to file names, such as
main-4F2K9XQ1.js, so a changed file gets a new name. - Checks the size budgets described below.
The result goes to dist/task-list/browser/. The output looks like this, though your hashes and chunk names will differ:
dist/task-list/browser/
index.html
main-4F2K9XQ1.js
polyfills-FFHMD2TL.js
styles-5INURTSO.css
favicon.ico
3rdpartylicenses.txtEverything in browser/ is static. Any server that can return files can host it. No Node.js process is needed at runtime.
Build configurations
The angular.json file defines named configurations for the build target. A new project has two. The exact keys vary a little between Angular versions, so treat this as a sketch:
"build": {
"builder": "@angular/build:application",
"options": {
"outputPath": "dist/task-list",
"index": "src/index.html",
"browser": "src/main.ts",
"tsConfig": "tsconfig.app.json"
},
"configurations": {
"production": {
"budgets": [
{ "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" },
{ "type": "anyComponentStyle", "maximumWarning": "2kB", "maximumError": "4kB" }
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
}The production configuration sets almost nothing explicitly because optimization is on by default. The development configuration turns optimization off and source maps on. You can run it with a flag:
ng build --configuration developmentUse this when you need to inspect the unminified output. Do not deploy it. It is several times larger and has no hashing.
Reading the build report
At the end of a build, the CLI prints a table of the files it wrote and their sizes. Look at two columns:
| Column | Meaning |
|---|---|
| Raw size | The file size on disk after minification. |
| Estimated transfer size | The approximate size after gzip or brotli compression, which is what the user downloads. |
Files in the "Initial chunks" group load before the app can start. Files in "Lazy chunks" load only when a route or @defer block needs them. For the task list app, main holds your components and services plus the parts of Angular you use. Keep an eye on this number, because it grows as you add libraries.
Budgets
A budget is a size limit that the build enforces. The initial budget above warns when the initial bundle passes 500 kB and fails the build at 1 MB. The anyComponentStyle budget limits the CSS of a single component.
A budget error exits the command with a non-zero code. That makes budgets a cheap guard in continuous integration (CI): a pull request that adds a large dependency fails before it ships. When a budget fails, you have three choices:
- Remove or replace the dependency that caused the growth.
- Move rarely used code behind a lazy route or
@deferblock. - Raise the limit, if you have decided the larger size is acceptable.
Option 3 is legitimate, but do it deliberately and not just to turn the build green.
Pointing the app at the right API
The TaskApi service from the HTTP chapter calls /api/tasks. This is a relative URL, so the browser sends the request to whichever host served the page. That works in production if your web server forwards /api/ to the backend, as shown in the next section. It avoids cross-origin (CORS) configuration and needs no per-environment code.
If the backend lives on a different origin, you need a value that changes between builds. Angular's ng generate environments command creates src/environments/environment.ts for production and environment.development.ts for development, and adds a fileReplacements entry to the development configuration so ng serve uses the development file.
// src/environments/environment.ts
export const environment = {
apiUrl: 'https://api.example.com',
};import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Task } from './task';
import { environment } from '../environments/environment';
@Injectable({ providedIn: 'root' })
export class TaskApi {
private readonly http = inject(HttpClient);
getTasks(): Observable<Task[]> {
return this.http.get<Task[]>(`${environment.apiUrl}/api/tasks`);
}
}The value is compiled into the bundle. Anything in it is visible to every user, so never put secrets such as API keys or passwords there.
Serving the build and the deep-link problem
Test the production build locally before deploying it. A simple static server is enough:
ng build
npx serve -s dist/task-list/browserThe -s flag tells serve to run in single-page-app mode. Without it, you will see the main failure of Angular deployments. Open the app at /, click into a task, and it works at /tasks/3. Now reload the page. The server looks for a file at tasks/3, finds nothing, and returns a 404.
The router only runs inside the browser, after index.html has loaded. The server knows nothing about /tasks/3. The fix is a fallback rule: any path that is not a real file returns index.html, and then the router takes over. Here is the same rule in nginx, together with the API forwarding and caching:
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://backend:3000;
}
location = /index.html {
add_header Cache-Control "no-cache";
}
location ~* \.(js|css)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
}The caching rules rely on file name hashing. A hashed JavaScript or CSS file never changes, so browsers can keep it for a year. index.html has a stable name and points at the current hashed files, so it must always be revalidated. If index.html is cached too long, users keep loading old bundles, or they request old file names that no longer exist.
Deploying under a sub-path
If the app is served from https://example.com/task-list/ and not from the domain root, set the base href at build time:
ng build --base-href /task-list/The base href tells the browser and the router how to resolve relative URLs and routes. If you leave it as /, the page loads but the script and style requests go to the wrong place and fail. The value must start and end with a slash.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Blank page, console errors loading `main-*.js` | Wrong base href for the deployment path | Rebuild with the right `--base-href`. |
| 404 on reload at `/tasks/3` | No fallback to `index.html` | Add the server fallback rule. |
| Build fails with a budget error | Bundle or component style over the limit | Reduce size, or raise the limit deliberately. |
| Users see an old version after a deploy | `index.html` cached too long | Serve `index.html` with `no-cache`. |
| API calls return `index.html` | The fallback rule also catches `/api/` | Put the `/api/` location before the fallback. |
| Works in `ng serve`, fails in `ng build` | Template type errors that development was lenient about, or a private member used in a template | Fix the error the build reports. |
Optional checks before shipping
- Run
ng test --watch=falseso a failing test stops the release. - Open the app from the built files with the browser developer tools on the Network tab. Confirm that JavaScript and CSS arrive compressed and that API calls reach the backend.
- Reload on a deep link, such as
/tasks/1, to confirm the fallback rule works. - Check that no source maps or
.env-style files ended up in the folder you upload.
Exercise
You deploy the built app to a static host. The list page loads, and clicking a task opens /tasks/3 correctly. Reloading the browser on /tasks/3 shows a 404 page from the server. Why does this happen, and what is the fix?
Show answer
The router runs only in the browser after index.html loads. When you reload, the browser asks the server for the path /tasks/3, and no file exists at that path, so the server returns 404. The fix is a server rule that returns index.html for any path that is not an existing file, for example try_files $uri $uri/ /index.html; in nginx. Once index.html loads, the Angular router reads the URL and shows the detail view.
Exercise
A teammate adds a charting library and ng build now fails with a budget error on the initial bundle. Name two ways to fix it that keep the budget meaningful, and one that you should avoid doing by default.
Show answer
Two good fixes: load the chart code lazily, for example behind a lazy route or an @defer block, so it leaves the initial bundle. Or replace the library with a smaller one. The option to avoid by default is raising maximumError until the build passes, because it removes the protection the budget gives. Raise it only after deciding the larger size is acceptable.
Exercise
Why can the server mark main-4F2K9XQ1.js as cacheable for a year but must not do the same for index.html?
Show answer
The file name contains a hash of its content. If the content changes, the next build produces a different name, so a cached copy is never stale. index.html keeps the same name on every build and is the file that references the current hashed files. If browsers cache it for a long time, they keep loading old bundles after a deploy.