You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Service Worker使用--base-href构建失效问题的解决方案咨询

Fixing Angular Service Worker Issues When Deploying to a Subpath

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 serviceWorker is turned on in your angular.json under 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:24:01