1. 添加 Workbox

    首先要下载 workbox-webpack-plugin 这个插件,然后在 webpack 配置文件中配置好插件

    1. const WorkboxPlugin = require('workbox-webpack-plugin');
    2. module.exports = {
    3. plugins: [
    4. new WorkboxPlugin.GenerateSW({
    5. // these options encourage the ServiceWorkers to get in there fast
    6. // and not allow any straggling "old" SWs to hang around
    7. clientsClaim: true,
    8. skipWaiting: true,
    9. })
    10. ]
    11. }
    1. 注册 Service-Worker

    service-worker.js 在 webpack 打包的时候会被打包出来,想要实现离线浏览,我们还需要注册一下这个 Service-Worker

    1. if ('serviceWorker' in navigator) {
    2. window.addEventListener('load', () => {
    3. navigator.serviceWorker.register('/service-worker.js').then(registration => {
    4. // 注册成功
    5. console.log('SW registered: ', registration);
    6. }).catch(registrationError => {
    7. // 注册失败
    8. console.log('SW registration failed: ', registrationError);
    9. });
    10. });
    11. }