Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Building and deploying

ng serve is handy for development, but a real server gets the built version: the code is minified, unused parts removed, and the files are ready to be served. After a build an Angular application is just a set of static files: HTML, JavaScript and CSS. Any web server can serve them.

Building

ng build

By default the build runs in production mode: the code is minified and debug checks are off. The terminal shows a table of files with sizes — initial files and lazy ones (Lazy chunk files) listed separately.

The result goes into the dist folder:

dist/my-app/
└── browser/
    ├── index.html
    ├── main-ABCD1234.js
    ├── styles-EFGH5678.css
    └── favicon.ico

You copy the contents of dist/my-app/browser to the server. The letters in file names are a fingerprint of the content: after a new build the names change, so the browser does not use an old cached version.

Checking the build locally

It is worth opening the build before deploying. Any static server will do, for example the serve package:

npx serve dist/my-app/browser -s

The -s flag turns on single-page application mode. Open the address from the terminal (usually http://localhost:3000) — the application works just like under ng serve.

Server setup

Angular routes exist only in the browser. If a user opens /posts/1 directly or reloads the page, the server looks for a file posts/1 and returns 404. So the server is configured like this: if there is no such file, serve index.html. For nginx it is one line:

location / {
    try_files $uri $uri/ /index.html;
}

Netlify, Vercel, Firebase Hosting and similar services do this with a single "single-page app" setting or a file with a redirect rule.

An application outside the site root

If the application will live at an address like https://example.com/blog/, set the base path when building:

ng build --base-href /blog/

The value goes into the base tag in index.html, and the browser loads files and builds route addresses from /blog/.

Settings for different environments

The API address on the development server and in production is often different. This command creates environment files:

ng generate environments
// src/environments/environment.ts
export const environment = {
  apiUrl: 'https://jsonplaceholder.typicode.com',
};

Next to it, environment.development.ts appears: ng serve uses it, and ng build uses the main file. Import environment in a service and take the address from environment.apiUrl.

Common mistake

Opening dist/my-app/browser/index.html by double-clicking it in the file manager. The page is blank, and the console shows script loading errors: the browser opens the file at a file:// address, where modules and routes do not work. Always check a build through a web server, as shown above.

Thanks for reading!

Donate to the site — we work hard for you.