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

如何让Service Worker自动缓存Vue构建生成的文件

解决Vue应用Service Worker自动缓存哈希文件名资源的问题

方法一:使用Vue CLI的PWA插件(推荐)

Vue CLI官方PWA插件集成了Workbox,能自动识别构建后带哈希的资源文件并配置缓存规则,无需手动维护toCache列表:

  1. 安装插件:
vue add pwa
  1. 在vue.config.js中可自定义缓存策略(可选):
module.exports = {
  pwa: {
    workboxOptions: {
      skipWaiting: true,
      clientsClaim: true,
      // 可添加自定义运行时缓存规则
      runtimeCaching: []
    }
  }
}
  1. 构建项目后,插件会自动生成包含所有哈希资源的Service Worker文件,无需手动修改sw.js。

方法二:自定义Service Worker动态获取缓存列表

若想保留现有自定义sw.js,可通过构建时生成资源清单,再让Service Worker加载清单实现动态缓存:

步骤1:构建时生成资源清单

在vue.config.js中添加webpack配置,生成包含所有构建后资源的清单文件:

const { WebpackManifestPlugin } = require('webpack-manifest-plugin');

module.exports = {
  configureWebpack: {
    plugins: [
      new WebpackManifestPlugin({
        fileName: 'asset-manifest.json',
        publicPath: ''
      })
    ]
  }
}

构建完成后,dist目录会生成asset-manifest.json,包含所有资源的路径信息。

步骤2:修改Service Worker加载清单

更新sw.js,在install事件中先获取资源清单,再合并固定缓存项进行缓存:

console.info('Service worker is running')

const assetCache = "asset";
const contentCache = "content";
const manifestUrl = 'asset-manifest.json';

self.addEventListener('install', function (event) {
  event.waitUntil(
    fetch(manifestUrl)
      .then(response => response.json())
      .then(manifest => {
        // 合并哈希资源与固定缓存项
        const toCache = [
          ...Object.values(manifest),
          'images/favicon.ico',
          'manifest.json',
          'images/icons/icon-128x128.png',
          'images/icons/icon-144x144.png',
          'images/icons/icon-152x152.png',
          'images/icons/icon-192x192.png',
          'images/icons/icon-512x512.png',
          'images/icons/icon-72x72.png',
          'images/icons/icon-96x96.png',
          'sw.js',
          'reg_sw.js'
        ];
        return caches.open(assetCache).then(cache => cache.addAll(toCache));
      })
  );
});

// 保留并优化原fetch事件逻辑
self.addEventListener('fetch', event => {
  const req = event.request;
  // 优先从缓存读取资源
  caches.match(req).then(cachedResponse => {
    if (cachedResponse) {
      event.respondWith(cachedResponse);
      return;
    }
    // 缓存新请求的资源
    event.respondWith(
      fetch(req)
        .then(resp => {
          const copy = resp.clone();
          event.waitUntil(
            caches.open(assetCache).then(cache => cache.put(req, copy))
          );
          return resp;
        })
        .catch(err => {
          if (req.headers.get('Accept').includes('text/html')) {
            return caches.open(assetCache).then(cache => cache.match(req));
          }
          return caches.match(req);
        })
    );
  });
});

每次构建后,Service Worker会自动加载最新资源清单,完成所有哈希文件名资源的缓存。


内容的提问来源于stack exchange,提问作者Jerome Palayoor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:42:41