Basics Of Angular Universal

In this article, we will learn the basics of Angular Universal. Angular Universal enables Server-Side rendering of Angular applications. An Angular application is run in a browser in the client-side but Angular Universal enables the Angular application to run on the server. In an Angular application, we bring the data from the server to the client and build HTML for the data in the client-side. Angular Universal allows us to do the same on the server.
 
According to the Angular official website, "Angular Universal is a technology that renders Angular applications on the server".
 
Basic of Angular Universal
 
Step 1
 
Create an Angular project by using the following command.
 
ng new Test
 
Basic of Angular Universal
 
Step 2
 
Open the newly created project in Visual Studio Code and open the terminal. Add the following command to create server-side modules.
 
ng add @nguniversal/express-engine --clientProject Project-Name
 
Basic of Angular Universal
 
It will take some time to install packages via npm.
 
Basic of Angular Universal
 
After installing, check some new files created, such as -
 
main.server.ts
 
This is bootstrapper for server app.This file exports the AppServerModule.
  1. import { enableProdMode } from '@angular/core';     
  2. import { environment } from './environments/environment';    
  3. if (environment.production) {    
  4.   enableProdMode();    
  5. }    
  6. export { AppServerModule } from './app/app.server.module';    
app.server.module.ts
 
This file is the root module for the server side app.
  1. import { NgModule } from '@angular/core';    
  2. import { ServerModule } from '@angular/platform-server';    
  3.     
  4. import { AppModule } from './app.module';    
  5. import { AppComponent } from './app.component';    
  6. import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';    
  7.     
  8. @NgModule({    
  9.   imports: [    
  10.     AppModule,    
  11.     ServerModule,    
  12.     ModuleMapLoaderModule,    
  13.   ],    
  14.   bootstrap: [AppComponent],    
  15. })    
  16. export class AppServerModule {}   
tsconfig.server.json
 
This file is for TypeScript server configuration.
 
webpack.server.congif.js
 
This is the webpack server configuration file.
 
server.ts
 
This is the NodeJS Express server file.
 
Basic of Angular Universal
 
Package.json
 
In package.json file, some new dependencies are added and new scripts: “compile:server”, “serve:ssr”, “build:ssr”, “build:client-and-server-bundles” added.
 
Basic of Angular Universal
 
Advantages of Angular Universal
  1. Improve the start up performance of our application.
  2. Search Engine Optimization
  3. Social Media Embedding
Summary
 
In this article, we learned the basics of Angular Universal, the folder structure of Angular Universal,  and the process of how to create an Angular Universal project.