Monday, 6 August 2018

Angular Progressive Web Apps

When in doubt refer to the Offical docs. When that doesn't work - try this manual fix it like I did!

Issues with Angular-cli

First it turns out that using ng add, as below, doesn't work very well.

ng add @angular/pwa --project project_name

I thought that maybe these issues were due a change in the Angular app file hierarchy (I changed "src" to "web"). I don't think this was the problem because many other people got stuck on the same error here and here.

Error highlighted below:
Installing packages for tooling via npm.
+ @angular/pwa@0.7.2
added 2 packages in 12.443s
Installed packages for tooling via npm.
Path "/ngsw-config.json" already exist.
I was able to get going by looking to see what this process is suppose to do.

Luckily it doesn't do a great deal and it is possible to find the files by searching your node_module directory then pasting them in before changing the parameters to suit your project - for example: ngsw-config.json to the code root and manifest.json to the /src directory. 

I was also able to better understand what the process should do by looking closely at this git commit. Notice the process adds:
"buildOptimizer": true,
"serviceWorker": true

to angular.json then adds the manifest.json before referencing it in the index.html:
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#1976d2">

Issues with testing service workers locally (A bad HTTP response code (404) was received when fetching the script)

This is a message you are will most likely see when you are attempting use the angular cli server and PWA. Probably running:

ng serve --prod

This is again a heavily documented issue yet that didn't stop me scratching my head.

ng serve will not run the required service worker compilation only ng build will do that - see.

This article also goes on to explain that only secure origins are allowed for service workers. Please consider whether it is worth the time to get this working too. The chances are that the project will work on a secure, encrypted site already now, if deployed.

Finally, you may get "ngsw.json cannot be found" or "manifest.json cannot be found". This can be remedied in Azure at least by allowing JSON MIME type to be served by the web server. Bear in mind that any other JSON in your dist directory will also be accessible.

<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".json" mimeType="application/json" />
     </staticContent>
    </system.webServer>
</configuration> 

Is it true that service workers only work with transport layer security (TLS or SSL)

No, you can run locally with a local node instance. You can also run chrome with parameters to tell it to always consider localhost secure if you find issues with that. See the official documentation.

No comments:

Post a Comment