Sub topic 11
Running and building with ng serve and ng build
This chapter assumes you have created a workspace with ng new, can read the basic structure of angular.json, and know that the build target names a builder and holds options. You will learn what ng serve and ng build do, where their output goes, and which problems come up most often.
Two commands, two jobs
ng serve and ng build both compile your application, but they serve different purposes.
ng servebuilds the app in memory, starts a development server, and rebuilds when you save a file. It writes nothing to disk.ng buildcompiles the app once and writes the result to a folder, ready to deploy.
Both commands read their settings from angular.json. The CLI resolves a command such as ng build to the build target of your project, then runs the builder named in that target.
{
"projects": {
"my-app": {
"architect": {
"build": {
"builder": "@angular/build:application",
"options": { "browser": "src/main.ts" }
},
"serve": {
"builder": "@angular/build:dev-server",
"configurations": {
"production": { "buildTarget": "my-app:build:production" },
"development": { "buildTarget": "my-app:build:development" }
},
"defaultConfiguration": "development"
}
}
}
}
}The serve target does not repeat your build settings. Its buildTarget option points at the build target, so the dev server uses the same entry point, styles, and assets that ng build uses. The builder package name depends on your version. Angular 17 to 19 workspaces may show @angular-devkit/build-angular:application and @angular-devkit/build-angular:dev-server.
Running the development server
Start the server from the workspace root:
ng serveBy default it listens on http://localhost:4200. After the first build finishes, the terminal prints the address. Edit a component and save, and the browser updates without a manual reload.
Common options:
| Option | Effect |
|---|---|
| `--open` (or `-o`) | Opens the app in your default browser. |
| `--port 4300` | Uses another port. `--port 0` picks any free port. |
| `--host 0.0.0.0` | Listens on all network interfaces, for example to test from a phone. |
| `--configuration production` | Serves the production build settings. |
| `--proxy-config proxy.conf.json` | Forwards selected URLs to a backend, which avoids CORS errors in development. |
How rebuilds work
The server watches your source files. When one changes, the builder recompiles only what is affected and sends the update to the browser. Styles and templates can often be swapped in place, and the page keeps its state. Changes to TypeScript logic usually trigger a full page reload.
Proxying API calls
A frequent need is to call a backend running on another port. Create proxy.conf.json in the workspace root:
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}Then start the server with it:
ng serve --proxy-config proxy.conf.jsonA request from the app to /api/products now goes to http://localhost:3000/api/products. The browser sees one origin, so no CORS headers are needed. This applies only to ng serve. A deployed app needs its own routing, for example a reverse proxy.
Building for deployment
Run a build with:
ng buildThe default configuration of the build target in a new workspace is production. The command applies production optimizations and writes files to dist/my-app. In recent versions the browser files are placed in dist/my-app/browser. Check the folder your version produces before you point a web server at it.
The production configuration typically does the following:
- Minifies JavaScript and CSS, and removes unused code (tree shaking).
- Adds a content hash to file names, such as
main-3F2A9C1B.js. This is controlled byoutputHashing. A changed file gets a new name, so browsers and CDNs cache old files safely without serving stale code. - Enforces size budgets, described below.
- Turns off source maps, so your original code is not shipped.
Choosing a configuration
Pass --configuration (or -c) to select a named set of overrides:
ng build --configuration developmentThe development configuration turns off optimization and enables source maps. The build is faster and the output is readable, but the files are large. Never deploy it.
To see the full result of a build, read the table the CLI prints. It lists each output file with its raw and estimated transfer size. The transfer size is the number to watch, since it approximates what users download.
Budgets: failing the build on size
A budget is a size limit checked at the end of a production build. A new workspace includes budgets in angular.json:
"budgets": [
{ "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" },
{ "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" }
]If the initial bundle goes past maximumWarning, the CLI prints a warning. Past maximumError, the build fails with a nonzero exit code, which also fails a CI job. When this happens, first find out why the bundle grew, for example a large library imported in full. Raising the limit hides the problem and should be a deliberate decision.
Watch mode and other useful flags
ng build --watch rebuilds on every change and writes to disk. It is useful when another tool serves the files, but for normal work ng serve is faster because it keeps the output in memory.
Other flags worth knowing:
--output-path dist/customchanges the output folder.--base-href /shop/sets the<base href>for apps deployed under a sub-path. Without it, assets and routes fail to load there.--stats-jsonwrites a stats file for bundle analysis tools.
Common errors and edge cases
- Port already in use. Another process holds 4200. Stop it, or run
ng serve --port 4300. - Blank page after deployment under a sub-path. The base href is wrong. Rebuild with
--base-href. - Refreshing a route returns 404 in production. The static server does not know about client-side routes. Configure it to return
index.htmlfor unknown paths.ng servealready does this, which is why the problem appears only after deploy. - Works in
ng serve, fails inng build. The production build is stricter and applies optimization. Runng buildbefore you push, not onlyng serve. - Changes are not picked up. Some network drives and container volumes do not send file events. Run
ng serve --poll 2000to check for changes every 2000 ms. - Out-of-date output.
distis not cleaned by hand. The builder removes the old output folder for you on each build, so do not store your own files there.
Summary of the workflow
A typical loop is to run ng serve while you develop, run ng build before a commit or in CI, and inspect the dist folder only when you need to check what will ship. Configurations in angular.json let both commands share one set of options while differing where they must.
Exercise
A teammate says the app works with ng serve but the page is blank when deployed to https://example.com/shop/. Which ng build option is the likely fix, and why?
Show answer
Use ng build --base-href /shop/. The app is served from a sub-path, so the <base href> must be /shop/. With the default /, the browser requests scripts and assets from the site root, where they do not exist.
Exercise
Your production build fails after you add a charting library, and the message mentions a budget. Name two ways to respond, and say which to try first.
Show answer
Try first to find out why the bundle grew, for example by importing only the parts of the library you use or loading the chart code lazily. The second option is to raise maximumError in the budgets entry of angular.json, which should be done only if the larger size is acceptable.