首页 > 解决方案 > 带有 webpack.js 的渐进式网络应用程序

问题描述

在 webpack.js 版本 5 中,我想使用 PWA,根据他们的 webpack 文档: https ://webpack.js.org/guides/progressive-web-application/ 我被告知使用 Workbox,但 Workbox 仅用于离线模式,比如如果我想使用Notifications、IndexedDB等其他功能,我应该在webpack.config.js中添加什么代码以及如何使用manifest.json和webpack?

标签: progressive-web-appsworkboxwebpack-5

解决方案


假设您想要https://webpack.js.org/guides/progressive-web-application/ 中描述的预缓存行为并且您想要自定义您的服务工作者,最干净的方法是使用, 并将路径传递给您的自定义服务工作者文件作为选项。InjectManifest workbox-webpack-pluginswSrc

InjectManifest插件将负责捆绑您的swSrc文件,并将self.__WB_MANIFEST根据您的webpack编译资产替换为预缓存清单。

// webpack.config.js

const path = require('path');
const {InjectManifest} = require('workbox-webpack-plugin');

module.exports = {
  // Your other webpack config goes here.
  plugins: [
    new InjectManifest({
      swSrc: './service-worker.js',
      swDest: 'service-worker.js',
      // Any other config if needed.
    }),
  ],
};
// service-worker.js

import {precacheAndRoute} from 'workbox-precaching';
// Add in additional imports here as needed.

// This line of code ensures that everything in your webpack
// compilation gets precache and served.
precacheAndRoute(self.__WB_MANIFEST);

// Your custom service worker code goes here.

推荐阅读