Angular Service Worker使用--base-href构建失效问题的解决方案咨询
It sounds like the Angular Service Worker (ngsw) isn’t correctly accounting for your app being deployed under the /test subpath. Let’s walk through the steps to resolve this:
1. Add baseHref to your ngsw-config.json
The key missing piece here is explicitly telling the service worker about your deployment subpath. Open your ngsw-config.json file and add the baseHref property at the top level, matching the value you used in your build command:
{ "baseHref": "/test/", "index": "/index.html", "assetGroups": [ // ... your existing asset groups configuration ] }
This ensures the service worker generates and uses paths prefixed with /test/ for all cached assets, aligning perfectly with your deployment location.
2. Verify Your Build & Service Worker Setup
Double-check that your project configuration is correctly enabled for the service worker:
- Your existing build script is correct:
"build": "ng build --prod --base-href /test/" - Ensure
serviceWorkeris turned on in yourangular.jsonunder the build options for your project:"projects": { "your-project-name": { "architect": { "build": { "options": { "serviceWorker": true, "ngswConfigPath": "src/ngsw-config.json" // ... other build options } } } } }
3. Confirm Deployment Structure
Make sure your built app files (from the dist folder) are deployed to the /test directory on your server. When you navigate to localhost:3000/test, the server should serve the index.html file from the dist folder placed under /test.
4. Clear Browser Cache & Old Service Workers
Old service workers or cached assets can cause persistent conflicts. Do the following to reset everything:
- Open your browser’s DevTools (F12)
- Go to the Application tab
- Under Service Workers, unregister any existing service workers linked to your app
- Under Cache Storage, clear all cached data related to your app
- Hard reload the page (Ctrl+Shift+R or Cmd+Shift+R)
After completing these steps, rebuild your app with npm run build and redeploy. The service worker should now correctly handle paths under /test/, eliminating the errors you’re seeing.
内容的提问来源于stack exchange,提问作者SashaSemanyuk

