Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pre-render pages in static HTML for an Angular app?

Tags:

angular

WHAT: I am building a website with Angular and I’d like to deploy it on a purely static server (such as Amazon S3). I need to pre-render all HTML pages for the site before deployment and I’m not sure how to proceed.

HOW: My current idea is to have some crawler read a file like sitemap.xml to retrieve a list of all the site’s URLs, then send requests for these URLs to a server where Node.js is installed and an instance of my Angular (Universal) app is running.

QUESTION: Does it sound like the proper way to do it? Am I missing an important step? Are there any libraries or npm packages that could help in this task?

Surprisingly, I couldn’t find any documentation about pre-rendering for Angular (only RE-rendering). I’ve also looked at static site generators for inspiration, but they all use a bunch of static files as their starting point (NOT a list of URLs). Also, I don't want to use a third-party service like prerender.io.

like image 516
AngularChef Avatar asked Jan 23 '17 10:01

AngularChef


1 Answers

I've just completed similar task using Angular 4. Site is hosted using Github pages and has no backend. Feel free to use it as example: repo and commit which implements pre-rendering: 0d81d28

I had to implement following changes:

  • Create server app module and update browser app module as described in angular universal guide
  • Implement pre-renderer script. Pre-renderer inspects router configuration and retrieve available app routes.
  • For each URL pre-render generates html file using renderModuleFactory from @angular/platform-server module and saves generated html in appropriate location.
  • As Bhargav mentioned static files server won't support any URL. So if you need to have URL like /community/overview then html should be saved into /community/overview/index.html. Angular matrix params wan't work :( . I had to move matrix params into URL route e.g. instead of /docs;doc=overview.html use /docs/overview.html
  • In order to fix annoying flickering after page loading, add initialNavigation: 'enabled' into router configuration: RouterModule.forRoot([{ path: '', ...}], { initialNavigation: 'enabled' }). I still have no idea what initialNavigation is and why it helps.

Hope this helps.

like image 163
Alexander Matyushentsev Avatar answered Oct 14 '22 11:10

Alexander Matyushentsev