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

Angular添加PWA后出现模块脚本MIME类型错误导致白屏

Angular PWA 重启标签页白屏 + MIME类型错误解决方案

问题核心

首次加载正常,但Service Worker缓存了错误资源(或服务器返回资源的MIME类型不符合预期),导致二次加载时脚本被识别为text/html触发加载失败;强制刷新会绕过缓存直接拉取服务器资源,因此能正常访问。

解决方案

1. 修正 ngsw-config.json 缓存规则

打开项目根目录的ngsw-config.json,确保JS/CSS文件被正确归类,避免被错误缓存为HTML:

{
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
        ]
      }
    }
  ]
}
  • 重点确认"/*.js"和"/*.css"规则存在,保证脚本文件被按正确类型缓存。
  • 若自定义了dataGroups,检查是否误将静态脚本纳入动态内容缓存规则。

2. 配置服务器正确的MIME类型

确保服务器对.js文件返回application/javascript类型:

  • Nginx:在站点配置中添加/确认:
    http {
      types {
        application/javascript js;
        # 其他MIME类型配置...
      }
    }
    
  • Apache:在项目根目录.htaccess中添加:
    AddType application/javascript .js
    
  • IIS:在站点MIME类型设置中,新增.js对应application/javascript。

3. 清除旧Service Worker缓存

旧的错误缓存可能残留,需彻底清理:

  1. 打开浏览器开发者工具(F12),切换到Application标签页。
  2. 左侧菜单找到Service Workers,选中当前站点的Service Worker,点击Unregister。
  3. 重新用生产环境命令构建部署:ng build --configuration production(Angular 12+)或ng build --prod(旧版本)。

也可在应用中加入自动更新检测,无需用户手动操作:

// app.component.ts
import { Component, OnInit } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private swUpdate: SwUpdate) {}

  ngOnInit(): void {
    if (this.swUpdate.isEnabled) {
      this.swUpdate.checkForUpdate().then(() => {
        this.swUpdate.available.subscribe(() => window.location.reload());
      });
    }
  }
}

4. 确认Angular构建配置

检查angular.json中生产环境是否开启Service Worker:

"projects": {
  "your-project-name": {
    "architect": {
      "build": {
        "options": {
          "serviceWorker": true
        },
        "configurations": {
          "production": {
            "serviceWorker": true
          }
        }
      }
    }
  }
}
  • 必须使用生产环境命令构建,开发模式的Service Worker不适合线上部署。

内容的提问来源于stack exchange,提问作者saeed-pasa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:40:24