1.我们需要在静态文件返回给浏览器的时候header中的缓存变长,这样就可以在本地秒加载,省去了带宽和加载时间
修改server.js
const path = require('path');
const Koa = require('koa');
const send = require('koa-send');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
// 匹配了所有url
router.get(['/', '/**'], async (ctx) => {
const url = ctx.path;
await send(ctx, './index.html', {
root: path.join(__dirname, 'dist'),
maxAge: 365 * 24 * 60 * 60 * 1000
});
})
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000);
这样,我们将文件的缓存时间改为十年,当然也可以改为永久,看心情
2.但是这样,如果更新了js,用户就没办法看到新的网页,永远在读缓存
我们改一下webpack,
webpack从0开始搭建react的ts开发环境
webpack.prod.ts
import path from "path";
import webpack from "webpack";
import {BundleAnalyzerPlugin} from "webpack-bundle-analyzer";
import merge from "webpack-merge";
import common from "./webpack.common";
const config: webpack.Configuration = merge(common, {
mode: "production",
devtool: "source-map",
output: {
filename: "app.[hash].js",
path: path.resolve(__dirname, "..", "dist"),
},
plugins: [
new BundleAnalyzerPlugin(),
],
});
export default config;
这样我们在运行
npm run build
的时候,生成的js会带有hash后缀,当我们没有更新代码的时候,hash不变,一旦更新代码,生成的hash也会跟着变化,这样就可以保证未更新时候的极致用户体验
css部分
webpack.common.ts
...
plugins: [
new HtmlWebpackPlugin({
title: "test",
template: path.resolve(__dirname,'template.html'),
}),
new MiniCssExtractPlugin({
filename: "app.[hash].css",
}),
],
...
3.但是还有一个问题,我们将html也缓存了,没办法获取新的html,就没办法拿到新的文件的hash
改一下server.js
const path = require('path');
const Koa = require('koa');
const send = require('koa-send');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router.get(['/', '/**'], async (ctx) => {
const url = ctx.path;
// 当访问静态文件的时候 十年缓存 用.来区分是url还是静态文件,别的方法也是可以的
if (url.includes('.')) {
await send(ctx, ctx.path, {
root: path.join(__dirname, 'dist'),
maxAge: 365 * 24 * 60 * 60 * 1000
});
}else{
await send(ctx, './index.html', {
root: path.join(__dirname, 'dist'),
maxAge: 0
});
}
})
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000);
网友评论