在使用 Angular v8 的 Service Worker 时,我总是遇到如下错误,这在 v7 中没有发生
以下是我的配置
package.json
"@angular/animations": "~8.2.14",
"@angular/common": "~8.2.14",
"@angular/compiler": "~8.2.14",
"@angular/core": "~8.2.14",
"@angular/forms": "~8.2.14",
"@angular/platform-browser": "~8.2.14",
"@angular/platform-browser-dynamic": "~8.2.14",
"@angular/pwa": "^0.900.2",
"@angular/router": "~8.2.14",
"@angular/service-worker": "~8.2.14",
角度.json
"assets": [
"src/assets/favicon.ico",
"src/assets",
"src/manifest.json"
],
"configurations": {
"production": {
// other is ommitted
"serviceWorker": true,
"ngswConfigPath": "ngsw-config.json"
}
}
ngsw-config.json
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/assets/favicon.ico",
"/manifest.json",
"/*.css",
"/*.js"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/images/**"
]
}
}
]
}
app.module.ts
imports: [
BrowserModule,
ServiceWorkerModule.register("ngsw-worker.js", {
enabled: environment.production
})
],
index.html
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#1976d2">
manifest.json
{
"name": "project",
"short_name": "project",
"theme_color": "#1976d2",
"background_color": "#fafafa",
"display": "standalone",
"scope": "/",
"start_url": "/",
"icons": [
{
"src": "assets/favicon.ico",
"sizes": "72x72",
"type": "image/ico"
},
{
"src": "assets/favicon.ico",
"sizes": "96x96",
"type": "image/ico"
},
{
"src": "assets/favicon.ico",
"sizes": "128x128",
"type": "image/ico"
},
{
"src": "assets/favicon.ico",
"sizes": "144x144",
"type": "image/ico"
},
{
"src": "assets/favicon.ico",
"sizes": "152x152",
"type": "image/ico"
},
{
"src": "assets/favicon.ico",
"sizes": "192x192",
"type": "image/ico"
},
{
"src": "assets/favicon.ico",
"sizes": "384x384",
"type": "image/ico"
},
{
"src": "assets/favicon.ico",
"sizes": "512x512",
"type": "image/ico"
}
]
}
请帮我指出我遗漏的地方。
非常感谢。
我发现了问题。网络可能不稳定,所以 Service Worker 无法注册。因此,要修复它,只需添加此配置
ServiceWorkerModule.register("ngsw-worker.js", {
enabled: environment.production,
registrationStrategy: "registerImmediately"
})
我想你可能已经错过了
“/index.html” “/assets/**”,或者您的资产可能位于单独的图像文件夹中(在看到文件夹结构之前我无法确定) “/*。(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)” 在
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/assets/favicon.ico",
"/index.html",
"/manifest.json",
"/*.css",
"/*.js"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
]
}
}
]
}
除此之外似乎没有什么区别。尽管如此,我已经尝试了与您相同的配置,并且运行正常。
你需要使用
"ngswConfigPath": "src/ngsw-config.json",
而不是
"ngswConfigPath": "ngsw-config.json",