之所以要进行缓存配置,是为了解决两个问题:1、项目发版后,由于客户端缓存,有时会导致用户需要清除缓存才能获取到最新的发版内容;2、减少获取新版本文件之后的客户端向服务端请求资源,从而加快前端的渲染。
一、方案
在经过前端cop头脑风暴之后,最终出具的缓存方案是:
1、index.html--->不缓存
2、js、css、img--->强制缓存
3、打包时css、js增加contenthash,合理利用打包进行缓存优化。
二、nginx配置
1、设置index.html不缓存
location / {
add_header Access-Control-Allow-Origin *;
root /usr/share/nginx/html/test;
if ($request_filename ~* .*\.(?:htm|html)$){
add_header Cache-Control no-store;
} #设置html不缓存
try_files $uri $uri/ @router;
index index.html index.htm;
#add_header Access-Control-Allow-Origin $cors_origin;
}
2、设置js、css、img强制缓存
map $sent_http_content_type $expires {
default off;
#text/html epoch; # 不缓存
text/css 30d; # 缓存30天,长时缓存可以设置为max
application/javascript 30d;
~image/ 30d;
}
server {
listen 80;
server_name localhost;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' '*';
add_header X-Frame-Options SAMEORIGIN;
add_header Access-Control-Allow-Credentials true;
expires $expires; #对不同的资源设置缓存
index index.html;
...
}
三、打包配置
css: {
sourceMap: false,
extract: {
// 打包后css文件名称添加contenthash
filename: `css/[name].[contenthash].css`,
chunkFilename: `css/[name].[contenthash].css`,
},
},
configureWebpack: () => {
return {
output: {
// 打包后js文件名称添加contenthash
filename: `[name].[contenthash].js`,
chunkFilename: `[name].[contenthash].js`,
},
};
},
ps:css更改会影响到通chunk的js,但js影响不到同chunk的css。
四、验证
1、index.html
示例(max-age=0或者no-store):
2、css、js、image
示例:
按道理来讲验证比图示来的复杂,不同的浏览器显示也会有差异,但是因为资源有限,所以仅以chorme简单展示配置成功之后的样子。
TIME!