- 添加 Workbox
首先要下载 workbox-webpack-plugin 这个插件,然后在 webpack 配置文件中配置好插件
const WorkboxPlugin = require('workbox-webpack-plugin');module.exports = {plugins: [new WorkboxPlugin.GenerateSW({// these options encourage the ServiceWorkers to get in there fast// and not allow any straggling "old" SWs to hang aroundclientsClaim: true,skipWaiting: true,})]}
- 注册 Service-Worker
service-worker.js 在 webpack 打包的时候会被打包出来,想要实现离线浏览,我们还需要注册一下这个 Service-Worker
if ('serviceWorker' in navigator) {window.addEventListener('load', () => {navigator.serviceWorker.register('/service-worker.js').then(registration => {// 注册成功console.log('SW registered: ', registration);}).catch(registrationError => {// 注册失败console.log('SW registration failed: ', registrationError);});});}
