离线缓存静态资源,快速开启网站,加快网站二次开启速度,秒开网站。
vue 打包添加 service worker。
webpack 打包添加 service worker。
只需引入插件并在打包时调用,无需其它任何操作,一件打包
Vue项目 或基于 Webpack 搭建的单页面应用,在打包时自动生成并插入 Service Worker 文件。
网站部署后,用户进入网站会自动安装 Service Worker,并按需加载并离线缓存项目文件,当项目更新时会立即刷新页面并重新离线缓存资源。
目前不支持跨域资源缓存。
您的项目要有 https 协议才能使 Service Worker 生效。
需要使用 service-worker-webpack-plugin 包,先进行安装:
npm install -D generate-service-worker-webpack-plugin
Vue 及 Webpack 项目可参考以下代码修改配置文件文件,
Vue项目如果没有 vue.config.js 可自己创建。
const GenerateServiceWorkerWebpackPlugin = require('generate-service-worker-webpack-plugin')
module.exports = {
// ...
configureWebpack: config => {
let plugins = []
if (process.env.NODE_ENV === 'production') {
plugins.push(new GenerateServiceWorkerWebpackPlugin({
// service worker 文件名称
name: 'sw',
// 版本号
version: '1.1.0',
// 匹配文件名,成功则不进行离线缓存
excache: /(\.map$|\.mp4$)/,
// 缓存大小在此范围内文件,单位:字节
size: [0, 1024 * 1024],
}));
}
config.plugins = [
...config.plugins,
...plugins
];
}
// ...
}
打包之后代码结构如下:
image.png
index.html文件里已经添加了引入sw.js的代码。
image.png