Prerendering Angular application

What is prerendering and how Angular Universal supports it? This lesson will answer that questio and show you what steps you need to take, to make your application prerenderable.

Prerendering#

You've already added the script to run pre-rendering of your application by executing the ng add @nguniversal/express-engine schematics. The problem is that it's not working with more sophisticated applications. Try to run it:

As you can see, you've run into several issues. Some dependencies are missing in the Dependency Injection mechanism:

Terminate the rendering process.

The point is that the pre-rendering mechanism does not launch your application through the server.ts file; it does not even launch the server. Because of that, providers passed to the ngExpressEngine function are not applied. You need to provide them inside the src/app/app.server.module.ts file. Add the following imports statements at the top of this file:

And provide services and tokens that are missing:

Note that you've also provided the REQUEST token used by the I18nService. The pre-rendering mechanism does not act like a browser, and it doesn't send HTTP requests to the server; because of that, no REQUEST object is provided automatically. You need to do it on your own.

There is one more issue that you've faced. The rendering process doesn't terminate. It's because of issue in the /node_modules/@nguniversal/builders/src/prerender/render.js file (in @nguniversal v. 10.1.0). The problem is that this script doesn't provide an exit code to the Node.js process:

That can be easily fixed by adding it:

Add the script in the package.json which will ensure that fix is applied. Adjust the prerender script so the check will be performed before any prerendering process:

Re-run prerendering:

It works! But... Angular pre-rendered only part of the routes in the application. The reason is that out of the box Angular analyzes routes declared in your application routing. Notice that routes to specific product landing pages are dynamic (they are parameterized based on the content stored in the database). If you want to add such routes to the pre-rendering process, you need to adjust the angular.json configuration file, and list them in the routes array of the projects.my-universal-app.architect.prerender.options entry:

 

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

No discussions yet