I am getting the following error
ERROR Error: Uncaught (in promise): TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
I used the prompt "ng add @angular/pwa" to add my ngsw-config.json and manifest file. This prompt also added my "serviceWorker" : true statement and my register with environment to my app.module.ts
After verifying everything was added properly I then ran the command "ng build --prod" that built successfully and the dist shown was made dist folder
Then I ran "ng serve --prod" and I am receiving the errors shown in the image errors
Line being used in app.module.ts
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
ngsw-configuration:
{
"index": "/",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
}, {
"name": "icons",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/icons/**"
]
}
}
]
}
Placement of serviceWorker true in angular.json:
"configurations": {
"production": {
"serviceWorker": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
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 your package.json scripts object.
Then run: ng build --prod --aot
, then npm 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 use http-server
. npm install http-server -g
. Then http-server ./dist -o
. This opens up your app on the default browser.