How to make Angular Universal and PWA work together?

ⅰ亾dé卋堺 提交于 2019-12-03 10:09:15

I have found a working solution, the navigationUrls property of ngsw-config.json contains a list of navigation URLs included or excluded (with an exclamation mark) like explained in the documentation.

Then I configured it like this:

"navigationUrls": [
    "!/**"
]

This way, none of the URLs redirect to index.html and the server-side rendered app comes into play when the app is first requested (or refreshed), whatever the URL is.

To go further, the three kinds of URLs managed by the service worker are:

  • Non-navigation URLs: static files cached by the service worker and listed in the generated ngsw.json file with their corresponding hashes
  • Navigation URLs: redirected to index.html by default, forwarded to the server if the "!/**" configuration is used
  • GET requests to the backend: forwarded to the backend

In order to distinguish a GET XMLHttpRequest from a navigation request, the service worker uses the Request.mode property and the Accept header that contains text/html when navigating and application/json, text/plain, */* when requesting the backend.

Edit:

This is actually not a good practice to do that for two reasons:

  • Depending on the network quality, there is no guarantee that the server-side version will render faster than the cached browser version
  • It breaks the "update in background" mechanism. Indeed, the server-side rendered app will always refer to the latest versions of the JavaScript files

For more details on this, please take a look at the Angular's team member answer to my feature request: https://github.com/angular/angular/issues/30861

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!