当前位置:首页 > VUE

vue打包实现http缓存

2026-02-24 12:59:17VUE

实现 Vue 项目打包后的 HTTP 缓存

配置 Webpack 输出文件名哈希

vue.config.js 中配置 Webpack 的 output.filenameoutput.chunkFilename 使用哈希值。这样每次文件内容变化时,哈希值会改变,确保浏览器获取最新文件。

module.exports = {
  configureWebpack: {
    output: {
      filename: '[name].[contenthash:8].js',
      chunkFilename: '[name].[contenthash:8].js'
    }
  }
}

设置静态资源缓存策略

在服务器配置中为静态资源设置长期缓存头。以下是 Nginx 的配置示例:

location / {
  try_files $uri $uri/ /index.html;
  expires 1y;
  add_header Cache-Control "public, max-age=31536000, immutable";
}

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
  expires 1y;
  add_header Cache-Control "public, max-age=31536000, immutable";
}

使用 Service Worker 缓存

通过 workbox-webpack-plugin 实现更精细的缓存控制:

vue打包实现http缓存

const { InjectManifest } = require('workbox-webpack-plugin')

module.exports = {
  configureWebpack: {
    plugins: [
      new InjectManifest({
        swSrc: './src/service-worker.js',
        swDest: 'service-worker.js'
      })
    ]
  }
}

配置 HTML 文件无缓存

确保 HTML 文件不被缓存,因为它是入口文件:

location = /index.html {
  expires -1;
  add_header Cache-Control "no-cache, no-store, must-revalidate";
}

使用版本号控制缓存

在项目发布时增加版本号,强制客户端获取新资源:

vue打包实现http缓存

// 在 main.js 中
const version = process.env.VERSION || '1.0.0'
localStorage.setItem('app_version', version)

// 检查版本更新
const oldVersion = localStorage.getItem('app_version')
if (oldVersion && oldVersion !== version) {
  caches.keys().then(cacheNames => {
    return Promise.all(
      cacheNames.map(cacheName => {
        return caches.delete(cacheName)
      })
    )
  })
}

配置 CDN 缓存

如果使用 CDN,需要配置合适的缓存规则:

  • 静态资源缓存时间设置为 1 年
  • HTML 文件设置为不缓存或短时间缓存
  • 启用自动刷新缓存功能

使用 ETag 验证

确保服务器配置了 ETag 或 Last-Modified 头,用于条件请求:

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
  etag on;
}

以上方法组合使用可以实现高效的 HTTP 缓存策略,同时确保用户总能获取到最新的应用版本。

标签: 缓存vue
分享给朋友:

相关文章

vue 实现关闭

vue 实现关闭

Vue 实现关闭功能的方法 在Vue中实现关闭功能通常涉及组件销毁、模态框隐藏或路由跳转等场景。以下是几种常见实现方式: 销毁当前组件 使用v-if或v-show控制组件显示/隐藏,适用于局部组件:…

vue实现翻译

vue实现翻译

Vue 实现翻译功能的方法 使用 i18n 插件实现多语言切换 安装 vue-i18n 插件: npm install vue-i18n 创建语言资源文件(如 en.json 和 zh.json):…

vue实现tap

vue实现tap

Vue 实现 Tap 事件 在移动端开发中,Tap 事件比 Click 事件更常用,因为 Click 事件有 300ms 延迟。以下是几种在 Vue 中实现 Tap 事件的方法。 使用第三方库 安装…

vue实现ppt

vue实现ppt

Vue 实现 PPT 的功能 Vue 可以结合第三方库或自定义组件实现类似 PPT 的演示效果。以下是几种常见的方法: 使用第三方库 reveal.js reveal.js 是一个流行的演示框架,支…

vue实现表单

vue实现表单

Vue 表单实现方法 双向数据绑定 使用 v-model 指令实现表单元素与数据的双向绑定。适用于 input、textarea、select 等元素。 <template> <…

vue实现甘特图

vue实现甘特图

使用 Vue 实现甘特图 基于开源库(如 vue-ganttastic) 安装依赖库: npm install vue-ganttastic 示例代码: <template> &l…