vue实现强缓存
Vue 实现强缓存的方法
强缓存通过 HTTP 响应头 Cache-Control 和 Expires 控制,浏览器在缓存有效期内直接使用本地资源,不发送请求到服务器。Vue 项目可以通过以下方式实现强缓存。
配置 Webpack 输出文件名哈希
在 vue.config.js 或 Webpack 配置中,为输出文件添加内容哈希。当文件内容变化时,哈希值改变,强制浏览器重新加载资源。
module.exports = {
configureWebpack: {
output: {
filename: '[name].[contenthash].js',
chunkFilename: '[name].[contenthash].js'
}
}
}
设置 Nginx 强缓存规则
在 Nginx 配置中,为静态资源设置 Cache-Control 响应头。通常对哈希命名的文件设置长期缓存,对非哈希文件禁止缓存。

location / {
try_files $uri $uri/ /index.html;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, no-transform, immutable";
}
使用 Service Worker 缓存策略
通过 workbox-webpack-plugin 或自定义 Service Worker 实现更灵活的缓存控制。在 vue.config.js 中配置:
const { InjectManifest } = require('workbox-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new InjectManifest({
swSrc: './src/service-worker.js',
swDest: 'service-worker.js'
})
]
}
}
在 Service Worker 中定义缓存策略
创建 src/service-worker.js 文件,使用 Cache API 实现强缓存逻辑:

const CACHE_NAME = 'my-app-cache-v1';
const urlsToCache = [
'/',
'/index.html',
'/static/js/main.[contenthash].js',
'/static/css/main.[contenthash].css'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
通过 HTTP 头控制缓存
确保服务器返回正确的 HTTP 响应头。对于哈希命名的静态资源,可设置长期缓存:
Cache-Control: public, max-age=31536000, immutable
对于 HTML 文件,通常禁用缓存或设置较短的有效期:
Cache-Control: no-cache, no-store, must-revalidate
使用 Vue CLI 的 PWA 插件
Vue CLI 的 @vue/cli-plugin-pwa 自动生成 Service Worker 并支持缓存策略。在 vue.config.js 中配置:
module.exports = {
pwa: {
workboxOptions: {
runtimeCaching: [
{
urlPattern: /\.(?:js|css|woff|woff2)$/,
handler: 'CacheFirst',
options: {
cacheName: 'static-resources',
expiration: {
maxEntries: 100,
maxAgeSeconds: 60 * 60 * 24 * 365
}
}
}
]
}
}
}






