Can you explain what’s actually happening under the hood?
Mrinal Purohit

Hi Mrinal

If you run the following commands:

ng new --style=scss cli-universal-demo
cd cli-universal-demo

You will see that ngc (@angular/compiler-cli) creates some files:

git status
>On branch master
>Untracked files:
> e2e/app.po.ngsummary.json
> src/app/app.component.ngfactory.ts
> src/app/app.component.ngsummary.json
> src/app/app.component.scss.shim.ngstyle.ts
> src/app/app.module.ngfactory.ts
> src/app/app.module.ngsummary.json
> src/environments/environment.ngsummary.json
> src/environments/

Those are the Ahead of Time (AOT) compiled files needed by the renderModuleFactory function

At my repo I added the src/app/app.server.module.ts and the src/server.ts

After run ngc again, it will generate the src/app/app.server.module.ngfactory.ts file, with the AppServerModuleNgFactory needed to bootstrap our app on the server.

The renderModuleFactory function have 2 parameters:

1) Is the class generated by ngc, in our case AppServerModuleNgFactory

2) Some options needed:

  • document: is a string with the content of our index.html file, I decided to use the index.html generated by ng build --prod, that comes with the scripts and style tags, I used readFileSync from the standard fs module from node to get the content of the index.hml file.
  • url: used by the router, to render the right page if you are using routing, I used req.url from express.

The server.ts file, is just a express server that listens on port 4000 and serves our static files and the server side rendered pages.

I run webpack to transform/bundle the server.ts to file to javascript, creating a server.js file, that I run with node.

node dist/server.js

Let me know if my explanation helped you, or if you still have some questions

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.