Vue CLI PWA 設定整理(實戰版)

官方文件:https://cli.vuejs.org/core-plugins/pwa.html


注意

  • Vue CLI 已進入 Maintenance Mode(建議新專案用 Vite)

  • PWA Plugin 可用但偏舊


核心概念

  • Service Worker 只在 production 生效

  • dev 模式會自動清 cache(noopServiceWorker)


設定位置

 
// vue.config.js
 
module.exports = {
 
  pwa: { ... }
 
}
 

核心設定

1️ workbox

 
pwa: {
 
  workboxPluginMode: 'GenerateSW' // 或 InjectManifest
 
}
 
模式說明
GenerateSW自動生成(簡單)
InjectManifest自訂 SW(進階)

2️ workboxOptions

 
workboxOptions: {
 
  swSrc: 'src/sw.js'
 
}
 

👉 僅 InjectManifest 使用


3️ App 基本資訊

pwa: {
 
  name: 'My App',
 
  themeColor: '#4DBA87',
 
  msTileColor: '#000000'
 
}

4️ iOS 支援

 
pwa: {
 
  appleMobileWebAppCapable: 'yes',
 
  appleMobileWebAppStatusBarStyle: 'black'
 
}
 

5️ manifest

 
pwa: {
 
  manifestOptions: {
 
    name: 'My App',
 
    short_name: 'App',
 
    start_url: '.',
 
    display: 'standalone',
 
    background_color: '#fff'
 
  }
 
}
 

6️ assetsVersion(更新 cache)

pwa: {
 
  assetsVersion: 'v1'
 
}

7️ iconPaths

pwa: {
  iconPaths: {
    favicon32: 'img/icons/favicon-32.png',
    appleTouchIcon: 'img/icons/apple.png'
  }
}

8️ manifestPath

pwa: {
 
  manifestPath: 'manifest.json'
 
}

9️⃣ manifestCrossorigin

 
pwa: {
 
  manifestCrossorigin: 'use-credentials'
 
}
 

🧩 完整範例

 
module.exports = {
 
  pwa: {
 
    name: 'Energy Dashboard',
 
    themeColor: '#0A1F44',
 
    msTileColor: '#000000',
 
  
 
    appleMobileWebAppCapable: 'yes',
 
    appleMobileWebAppStatusBarStyle: 'black',
 
  
 
    workboxPluginMode: 'GenerateSW',
 
  
 
    manifestOptions: {
 
      name: 'Energy Dashboard',
 
      short_name: 'Energy',
 
      start_url: '.',
 
      display: 'standalone',
 
      background_color: '#ffffff'
 
    },
 
  
 
    assetsVersion: 'v1'
 
  }
 
}
 

測試流程

 
npm run build
 
npx serve dist
 

👉 建議用無痕模式測試


常見問題

  • Dev 看不到 PWA → 正常

  • 更新沒生效 → 改 assetsVersion

  • 無法安裝 → 檢查 HTTPS / manifest / icon / SW


Dashboard 建議

  • 只 cache 靜態資源(JS/CSS)

  • API 不要 cache

  • 使用 stale-while-revalidate


進階

  • Push Notification

  • Background Sync

  • IndexedDB

  • WebRTC + PWA


建議

新專案改用:


vite-plugin-pwa