I used sw-precache
to generate a service worker for a Firebase
hosted Angular 2 app.
Error:
Service Worker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
Structure
src-
app--
index.html
service-worker.js
sw-precache-config.js
sw-precache-config.js
module.exports = {
navigateFallback: '../index.html',
stripPrefix: 'dist',
root: 'dist/',
staticFileGlobs: [
'dist/index.html',
'dist/**.js',
'dist/**.css'
]
};
index.html
<script>
if ('serviceWorker' in navigator) {
console.log(navigator.serviceWorker);
navigator.serviceWorker.register('service-worker.js').then(function (registration) {
console.log('Service Worker registered');
}).catch(function (err) {
console.log('Service Worker registration failed: ', err);
});
}
</script>
Your service worker registration code seems fine to me.The problem might be in the project structure.Since you have mentioned the root as dist folder, your service-worker.js file must be in the dist folder after you run the
ng build
script. Add"precache": "sw-precache --verbose --config=sw-precache-config.js"
to yourpackage.json
scripts object.Then run:ng build --prod --aot
,thennpm run precache
.Now your service-worker.js file would be present in the dist folder.Since the angular compiler has compiled your app code into js files and stored it in the dist folder ,now you must serve your app from the dist folder.But the default ng serve doesn't support it.I suggest you to usehttp-server
.npm install http-server -g
.Thenhttp-server ./dist -o
.This open up your app on default browser.