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

部署AWS S3后页面空白报404错误求助(含Vite PWA配置)

部署AWS S3的PWA项目提交PR后首次刷新空白(404)问题解决方案

问题描述

将Vue+Vite+PWA项目部署至http://develop.example.com,提交PR更新develop分支代码后,首次刷新页面出现全空白,控制台提示:

Failed to load resource: the server responded with a status of 404 () index-CR9SSg6k.js:1

再次刷新页面则恢复正常,部署目标为AWS S3。

相关配置与输出

Vite配置

export default defineConfig({
  plugins: [
    vue(),
    VitePWA({
      registerType: 'autoUpdate',
      injectRegister: 'inline',
      manifest: false,
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
        clientsClaim: true,
        skipWaiting: true,
        maximumFileSizeToCacheInBytes: 5000000
      },
    }),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    port: 3000,
  },
  preview: {
    port: 3000,
  },
})

构建输出(npm run build)

PWA v0.19.5
mode generateSW
precache 59 entries (1170.53 KiB)
files generated
dist/sw.js
dist/workbox-5357ef54.js
warnings
assets/index-DswbvO1k.js is 6.66 MB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit.

解决方案

1. 修复大文件未预缓存问题

从构建警告可知,index-DswbvO1k.js(6.66MB)超过了maximumFileSizeToCacheInBytes设置的5MB上限,导致未被预缓存。新部署的资源哈希变化后,旧Service Worker无法正确获取新资源,引发404。

调整VitePWA配置中的文件大小限制,比如设置为8MB:

workbox: {
  // 保留原有配置
  maximumFileSizeToCacheInBytes: 8 * 1024 * 1024 // 8MB
}

2. 优化Service Worker缓存策略

当前配置了skipWaiting: true和clientsClaim: true,但需添加旧缓存自动清理逻辑,避免旧资源干扰:

workbox: {
  // 保留原有配置
  cleanupOutdatedCaches: true
}

若需要更可靠的更新触发,可自定义SW注册逻辑,确保新SW激活后立即接管页面:

// 入口文件(如main.js)中添加
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(registration => {
    registration.addEventListener('updatefound', () => {
      const newWorker = registration.installing;
      newWorker.addEventListener('statechange', () => {
        if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
          window.location.reload();
        }
      });
    });
  });
}

3. AWS S3部署配置调整

  • 静态网站托管:将错误文档设置为index.html,避免路径或路由问题引发的404。
  • 缓存策略:
    • 哈希命名的资源(如index-CR9SSg6k.js):在S3对象元数据中设置Cache-Control: public, max-age=31536000, immutable,让浏览器长期缓存。
    • index.html:设置Cache-Control: no-cache,确保每次请求都获取最新版本。

内容的提问来源于stack exchange,提问作者Gonzalo A .A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:46:20