1. 对于使用 Vue CLI 创建的项目
可以通过配置 vue.config.js
中的 chainWebpack
来设置静态资源的缓存策略,然后结合服务器配置实现强缓存。
lua
// vue.config.js module.exports = { chainWebpack: config => { // 对第三方库设置长时间的缓存 config.output .filename('js/[name].[contenthash:8].js') .chunkFilename('js/[name].[contenthash:8].js') // 对图片等静态资源设置缓存 config.module .rule('images') .use('url-loader') .tap(options => { options.name = 'img/[name].[hash:8].[ext]' return options }) } }
2. 服务器配置(关键)
强缓存主要通过服务器设置 Cache-Control
和 Expires
响应头来实现。
Nginx 配置示例:
javascript
# 对 node_modules 中的第三方库设置强缓存(30天) location ~* /node_modules/(.*)\.(js|css)$ { expires 30d; add_header Cache-Control "public, max-age=2592000"; } # 对静态资源设置强缓存 location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { # 排除 index.html,避免其被缓存 if ($request_filename ~* ^.+\.(html)$) { expires -1; add_header Cache-Control "no-cache, no-store"; } # 其他静态资源缓存30天 expires 30d; add_header Cache-Control "public, max-age=2592000"; }
Apache 配置示例(.htaccess):
arduino
# 对第三方库和静态资源设置强缓存 <IfModule mod_expires.c> ExpiresActive On # 脚本和样式文件缓存30天 ExpiresByType text/css "access plus 30 days" ExpiresByType application/javascript "access plus 30 days" # 图片文件缓存30天 ExpiresByType image/jpeg "access plus 30 days" ExpiresByType image/png "access plus 30 days" ExpiresByType image/svg+xml "access plus 30 days" # 设置Cache-Control头 Header set Cache-Control "public" </IfModule>
3. 关键说明
-
强缓存原理 :通过设置
Cache-Control: max-age=xxx
或Expires
头,浏览器会在有效期内直接使用本地缓存,不向服务器发送请求 -
缓存有效期:第三方库(如 echarts、element-ui)更新频率低,可以设置较长缓存(如 30 天)
-
避免缓存问题:
-
对经常变动的文件(如 index.html)禁用缓存
-
使用内容哈希(contenthash)命名文件,确保文件内容变化时文件名变化,从而绕过缓存
-
对于可能更新的第三方库,建议使用 CDN 并利用其缓存策略
-
通过以上配置,既能实现第三方库和静态资源的强缓存以提高加载速度,又能确保在文件更新时用户能获取到最新版本。