Learn Angular · 14/14

Deployment & Optimization

8 min read

Deployment & Optimization

Welcome to the final stages of the Angular development lifecycle. You have crafted components, managed state, and handled routing. Now, the code must leave your local machine and exist on the World Wide Web.

This guide focuses on preparing your application for the real world. We will move from the comfort of localhost to production-grade deployment, ensuring your application is fast, discoverable, and accessible.


1. Managing Environments: Development vs. Production

The Problem

When developing locally, your API endpoints likely look like http://localhost:3000/api. However, when you deploy to a live server, that API might live at https://api.myapp.com. Hardcoding these values requires changing the code every time you deploy, which is error-prone and tedious. Furthermore, you may want detailed logging in development but strict silence in production to save memory.

The Solution: Environment Files

Angular provides a built-in mechanism to manage configuration variables based on the build target. This allows you to define distinct variables for development, staging, and production environments.

Implementation

Since Angular 15+, environment files are not generated by default to reduce boilerplate. You can generate them easily.

Step 1: Generate Environment Files
Run the following command in your terminal:

bash
ng generate environments

This creates a new folder src/environments/ containing:

  • environment.ts (Default/Development)
  • environment.development.ts

Step 2: Configuring Variables

Inside src/environments/environment.ts (This usually acts as your production base or interface):

typescript
// src/environments/environment.ts
export const environment = {
  production: true,
  apiUrl: 'https://api.my-production-app.com/v1',
  featureFlagNewUI: true
};

Inside src/environments/environment.development.ts:

typescript
// src/environments/environment.development.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000/v1',
  featureFlagNewUI: true
};

Step 3: Using Variables in Services
You import the environment object into your services or components. Angular's build process will swap the file content based on the configuration.

typescript
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../environments/environment'; // Always import the base file

@Injectable({ providedIn: 'root' })
export class DataService {
  constructor(private http: HttpClient) {}

  getData() {
    // Angular automatically uses the correct value based on the build
    return this.http.get(`${environment.apiUrl}/users`);
  }
}

Step 4: Configuration in angular.json
The angular.json file controls which file replaces which. Under architect -> build -> configurations -> production:

json
"fileReplacements": [
  {
    "replace": "src/environments/environment.ts",
    "with": "src/environments/environment.ts" 
  }
]

Note: In modern CLI versions, the development file is swapped in during ng serve, while the standard environment file is treated as production by default during ng build.

💡 Interesting Fact:
In the early days of web development, "deployment" often meant using an FTP client (File Transfer Protocol) to manually drag and drop files from a Windows folder to a remote Linux server one by one. If your internet disconnected halfway through, your site would be half-broken until you reconnected.


2. Building for Production: Ahead-of-Time (AOT) Compilation

The Problem

Browsers do not understand Angular specific syntax (like @Component decorators) or TypeScript files. They only understand JavaScript and HTML. Additionally, the Angular compiler itself is a large piece of software. If we ship the compiler to the browser to compile the code on the user's device (Just-in-Time or JIT compilation), the application takes longer to load because it must download the compiler and then process the code.

The Solution: AOT Compilation

Ahead-of-Time (AOT) compilation converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase, before the browser downloads and runs that code.

Key Benefits of AOT

  1. Faster Rendering: The browser downloads pre-compiled executable code. It renders immediately without waiting to compile the app first.
  2. Smaller Angular Framework Download Size: The Angular compiler is not included in the bundle because the code is already compiled.
  3. Template Type Checking: It detects template errors (like binding to a variable that doesn't exist) during the build process, rather than crashing at runtime.

Optimization Techniques

When you run the build command, Angular (via Webpack or esbuild) performs several other optimizations alongside AOT:

  • Tree Shaking: A process that removes unused code from the final bundle. If you import a library but only use one function, Tree Shaking removes the rest of the library from the final file.
  • Minification: Removing whitespace, comments, and shortening variable names (e.g., changing userName to a) to reduce file size.
  • Uglification: Obfuscating code logic to make reverse-engineering slightly more difficult (though primarily for size reduction).

Hands-on: Creating a Production Build

To build your application for production, run:

bash
ng build

This command:

  1. Compiles the project using AOT.
  2. Stores the result in the dist/ folder.
  3. Generates hash-named files (e.g., main.7a2b3c.js) to prevent browser caching issues when you deploy updates.

Output Example:

text
Initial Chunk Files | Names         |  Raw Size
main.5a7b8c.js      | main          | 145.32 kB
styles.2c3d4e.css   | styles        |  12.11 kB
runtime.8f9a0b.js   | runtime       |   1.05 kB

3. Server-Side Rendering (SSR): Angular Universal Basics

The Problem

By default, Angular is a Client-Side Rendered (CSR) framework. When a user visits your site, the server returns an HTML file that looks like this:

html
<html>
  <body>
    <app-root></app-root>
    <script src="main.js"></script>
  </body>
</html>

The browser screen is blank until main.js downloads and executes.

  1. SEO Issues: Search engine crawlers (bots) may see the empty <app-root> and assume the page has no content, hurting your search rankings.
  2. Performance (FCP): Users on slow connections see a white screen for several seconds before the UI "pops" into existence.

The Solution: Server-Side Rendering (SSR)

SSR generates the full HTML of a page on the server in response to a navigation request. The server sends a fully rendered HTML page to the browser. The user sees the content immediately. Then, Angular loads in the background and "hydrates" the page (attaches event listeners like clicks) to make it interactive.

In the Angular ecosystem, the technology handling this is traditionally called Angular Universal, though modern versions simply refer to it as Angular SSR.

Hands-on: Adding SSR

Angular makes converting a standard app to an SSR app extremely automated via the CLI.

Step 1: Add the SSR package
Run this command in your project root:

bash
ng add @angular/ssr

What this command does:

  1. Updates angular.json to enable server builds.
  2. Creates a server.ts file (an Express.js web server) to handle requests.
  3. Updates package.json scripts.

Step 2: Testing SSR Locally
Instead of ng serve, you can now run:

bash
npm run serve:ssr:YourAppName

Note: Check your package.json "scripts" section for the exact command name, as it varies slightly by version.

When you view the source code of your page in the browser (Ctrl+U), you will now see actual HTML content inside <app-root> instead of empty tags.

🧠 Concept Check: Hydration
Hydration is the process where the client-side JavaScript "wakes up" the static HTML sent by the server. It reuses the existing DOM elements rather than destroying and re-rendering them, preventing visual flickering.


4. Hosting Your App: Deploying to Vercel, Netlify, or Firebase

Once you have your dist/ folder (or your SSR setup), you need a cloud provider to host it. Here are three industry-standard options.

Option A: Firebase Hosting (Google Cloud)

Firebase is excellent for Angular apps as it is also maintained by Google.

  1. Install Firebase Tools:

    bash
    npm install -g firebase-tools
  2. Login:

    bash
    firebase login
  3. Initialize Project:
    Run this in your project root:

    bash
    firebase init
    • Select Hosting.
    • Select "Use an existing project" or "Create a new project".
    • Public directory: dist/your-project-name/browser (Verify the exact path in your dist folder).
    • Configure as a single-page app? Yes.
    • Set up automatic builds and deploys with GitHub? (Optional, but recommended for CI/CD).
  4. Deploy:

    bash
    ng build
    firebase deploy

Option B: Vercel

Vercel is popular for its "zero-configuration" deployments and excellent Git integration.

  1. Install Vercel CLI:
    bash
    npm i -g vercel
  2. Deploy:
    Inside your project root, simply run:
    bash
    vercel
  3. Configuration:
    Vercel will detect it is an Angular project.
    • It will ask usually simple Yes/No questions.
    • If asked for Output Directory, usually dist/your-project-name/browser is correct.

Alternatively, connect your GitHub repository to Vercel's dashboard, and it will auto-deploy every time you push code.

Option C: Netlify

Similar to Vercel, known for ease of use.

  1. Install Netlify CLI:

    bash
    npm install netlify-cli -g
  2. Build:

    bash
    ng build
  3. Deploy:

    bash
    netlify deploy

    It will ask for the "Publish directory". Enter: dist/your-project-name/browser.

  4. Production Deploy:
    If the draft looks good:

    bash
    netlify deploy --prod

Summary

  1. Environments: Use ng generate environments to keep API keys and configurations separate for Dev and Prod.
  2. AOT: Default in Angular. Converts TS/HTML to JS before the browser sees it.
  3. SSR: Use ng add @angular/ssr for better SEO and perceived performance.
  4. Hosting: Build your app (ng build) and upload the dist folder to Firebase, Vercel, or Netlify.

You have now successfully navigated the full Angular journey, from component creation to global deployment. 🌍

References & Further Reading

Challenge

You are a developer finalizing the deployment process for an Angular application named my-crm-app. Your task is to correctly configure the build environment and the hosting settings for Firebase within the provided JSON structure.

Part 1: Configure Production Environment

In the provided angular.json structure, modify the production configuration for the build architect. You need to ensure that when you run a production build, the standard environment.ts file is swapped with the production-specific environment.prod.ts.

Objective:

  • Add the fileReplacements property to the production configuration object.
  • This property should be an array containing an object that specifies the replacement of src/environments/environment.ts with src/environments/environment.prod.ts.

Part 2: Configure Firebase Hosting

In the firebase.json section of the code, create the necessary configuration to deploy your application.

Objective:

  • Define a hosting object.
  • Set the public property to the correct output directory for the browser build of your my-crm-app. The standard path is dist/my-crm-app/browser.
  • Configure the server to handle routing for a single-page application (SPA) by rewriting all unmatched URLs to /index.html.

Expected result

Your final submission should be a single valid JSON object containing the correctly configured angular.json and firebase.json sections.

In angular.json, the production configuration object must include a fileReplacements array structured as follows:

json
"fileReplacements": [
  {
    "replace": "src/environments/environment.ts",
    "with": "src/environments/environment.prod.ts"
  }
]

In firebase.json, the object should contain a hosting configuration pointing to the correct public directory and including a rewrite rule for a single-page application:

json
"hosting": {
  "public": "dist/my-crm-app/browser",
  "rewrites": [
    {
      "source": "**",
      "destination": "/index.html"
    }
  ]
}
json

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.