Applying Universal Schematics

The easiest way to enhance your Angular project with new functionalities is to use Schematics - a set of instruction for CLI on how to change the project and install new dependencies. Let's do that with Angular Universal and review what Schematics did for us.

Applying schematics#

Starting your adventure with Angular Universal is as simple as applying a single command using the Angular CLI. Navigate to your project root directory and type the following in the terminal:

Angular CLI will install all the necessary dependencies for you and apply schematics (a set of instructions on how to adjust the project). After applying the schematics, you should see the summary output of what has been changed, added, or deleted in your project:

Let's review these changes.

Dependencies and scripts#

The backbone of your project is the package.json file. Angular CLI has installed new dependencies there that are necessary to run Angular in the Node.js runtime environment:

Another change is in the scripts section:

Angular CLI has added the following new scripts:

  • dev:ssr is an equivalent of the ng serve command. You should use it for development purposes. The difference between npm run dev:ssr and ng serve is that the former will compile both server-side and browser-side code for you. This enables you to check how your application behaves in the server environment. Both solutions are watching your project for changes, so whenever you apply changes in code, they will automatically trigger the compilation process.

  • build:ssr is an equivalent of ng build --prod. This command should be used to compile the production-ready application. Once it is applied, you will see compilation output inside the dist//browser and dist//server folders in your project.

  • serve:ssr is used to serve the application in production mode. This script runs the compiled server source code, which resides in the dist//server folder.

  • prerender is a script that you can use to generate HTML and JavaScript for static hosting - we will cover this topic later in the course.

Builders#

Under the hood, the scripts described above use a set of builders added to your project. You can find them in the angular.json file:

As you can see, the server-side rendering build will use a new entry point to your application, server.ts.

Node.js application#

The server.ts file is where the Node.js application resides.

 

This page is a preview of The newline Guide to Angular Universal

No discussions yet