部署AWS S3后页面空白报404错误求助(含Vite PWA配置)
问题描述
将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

