How to run service worker locally with Angular

…衆ロ難τιáo~ 提交于 2020-06-12 09:02:46

问题


I am following angular's best practice in order to make PWA. After making production build (ng build --prod --aot), I am also running the service worker from dist, on localhost: http-server -p 8080 -c-1 dist When I am trying to sync the worker with my Angular, using:

navigator.serviceWorker.ready.then(function(swRegistration) {

            console.log('swReady');
});

Nothing happens, and seems that SW is not communicating with Angular. Working with a remote server (uploading dist) does work. So seems that the problem is dist not working with ng serve. What am I doing wrong?


回答1:


You can't serve your Angular project with service worker via ng serve, as the documentation for Service Workers state that it requires https. The only way to run it without https/on a server, is to use ng build and run the http-server locally to test your project.

Because ng serve does not work with service workers, you must use a separate HTTP server to test your project locally.




回答2:


It seems that currently we cannot use service worker with ng serve --prod. However we can make a workaround.

  1. We build the project ng build --prod

  2. From the dist location we take the ngsw-worker.js and ngsw.json files and copy them to the src folder.

  3. We modify our angular.json file in order to serve them. We find the property "projects": {"[my-project-name]": {... "architect": {... "build": {... "options": {... "assets": [... and there we add these two items – "src/ngsw-worker.js", "src/ngsw.json".

  4. We serve – ng serve --prod.

I have reached till that point. The browser says that the SW is activated and running. The only consideration now is that if we change something in the SW, we need to rebuild again and make the same steps. But I believe we can develop more rapidly.

Good luck!




回答3:


With Chrome, you can enable a flag for treating a specific host as if it is a secure origin, allowing service workers to work:

./chrome --unsafely-treat-insecure-origin-as-secure=http://your.insecure.site:8080

To launch chrome from the terminal, you do need to know the executable location. This will be system dependent. For MacOs:

open /Applications/Google\ Chrome.app/ --args  --unsafely-treat-insecure-origin-as-secure=http://your.insecure.site:8080



回答4:


If you want to use other browsers that don't support TimKVU answer then the solution is to use ngrok (https://ngrok.com)

It sets up a secure tunnel to whatever server you are using. You run it with:

ngrok http 4200

Simply connect to the domain shown on screen.



来源:https://stackoverflow.com/questions/55905172/how-to-run-service-worker-locally-with-angular

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