0

We have implemented PWA (@angular/service-worker) and in prod mode everything works as expected. We are using angular universal. But in dev mode, the file "ngsw-worker.js" is not generated.

I already changed the registration to enabled on all environments:

ServiceWorkerModule.register('./ngsw-worker.js', {
  enabled: true,
})

And of course it's added in angular.json:

  "projects": {
    "client-app": {
      ...
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "serviceWorker": true,
            "ngswConfigPath": "ngsw-config.json"
          }

But the file is still not generated, I cannot find any reference to this file in the code. We use "npm run dev:ssr" which is part of the angular universal template to run the app in development environment. My guess is that the serviceworker is not built with this command.

The browser shows this message since it cannot find this file and is trying to read the index file which it's redirected to:

home-routing.module.ts:19 Service worker registration failed with: DOMException: Failed to register a ServiceWorker for scope ('http://localhost:4200/') with script ('http://localhost:4200/ngsw-worker.js'): The script has an unsupported MIME type ('text/html').

We need to be able to test PWA features during development as well.

How can we add this file in dev build?

1 Answer 1

0

I found a way to test service-worker locally with Angular universal:

  • Run "npm run build" which compiles the browser script files.
  • Copy the files "ngsw.json, ngsw-worker.js, safety-worker.js, worker-basic.min.js" from "dist\<app>\browser"
  • Run "npm run dev:ssr" which will compile the browser and the server script files
  • Copy the files back to "dist\<app>\browser"

Now you have the scripts also when using the angular universal dev server.

Sign up to request clarification or add additional context in comments.

3 Comments

Does the browser register the service worker? As far as I'm aware, most browsers won't register one if you're not on HTTPS
They may certainly do it on localhost, which is treated as HTTPS by browsers
It does at least with chrome. Also you can also run Angular locally with ssl. Although I didn't manage to do it with angular universal (Seems to have a bug).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.