Prerender an Angular application with @angular/cli and puppeteer
If you have an static Angular application, that does not change its content very often, like a blog or any other static content website, you can use the new google chrome team project called puppeteer, to prerender your pages at build time.
Using puppeteer you can use any library you like in your angular application, like @angular/material, @angular/flex-layout, @ng-bootstrap/ng-bootstrap, PrimeNG, Ionic or any other, that not support server side rendering yet, because your application will be prerender in a headless Chromium instance at build time, and not in the server at run time, like my post before https://medium.com/@evertonrobertoauler/angular-4-universal-app-with-angular-cli-db8b53bba07d.
Let’s get started.
ng new --style=scss prerender-demo-app
cd prerender-demo-app
npm install --save @angular/material @angular/cdk @angular/animations
npm install --save-dev puppeteer express mz lodash npm-run-all
Now we create some pages for routing
ng g c pages/home
ng g c pages/about
Configure our src/app/app.module.ts
Update src/index.html
Update src/styles.scss
Update src/app/app.component.html
Update src/app/pages/home/home.component.ts
Update src/app/pages/home/home.component.html
Update src/app/pages/about/about.component.ts
Update src/app/pages/home/home.component.html
Create a file called prerender.js in the same folder as package.json
Update your package.json file
Now you just need to run
npm run build
Your project was build and prerendered in the `dist` folder, now you can just deploy it to Firebase Hosting, like the example bellow.
firebase.json
firebase deploy
Or if you are using your own server with Nginx, configure your website.conf file like the following example:
Try it out:
https://prerender-demo-app.firebaseapp.com/
https://prerender-demo-app.firebaseapp.com/about
Or clone my github repo:
git clone https://github.com/evertonrobertoauler/prerender-demo-app.git
cd prerender-demo-app
npm install
npm run build
Feel free to contact me if anything goes wrong.