推荐答案
// www.javascriptcn.com code example
const { GenerateSW } = require('workbox-webpack-plugin');
module.exports = {
// 其他 webpack 配置...
plugins: [
new GenerateSW({
clientsClaim: true,
skipWaiting: true,
runtimeCaching: [
{
urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
handler: 'CacheFirst',
options: {
cacheName: 'images',
expiration: {
maxEntries: 50,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 天
},
},
},
{
urlPattern: /\.(?:js|css)$/,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'static-resources',
},
},
],
}),
],
};本题详细解读
1. 什么是 workbox-webpack-plugin?
workbox-webpack-plugin 是一个用于在 Webpack 构建过程中自动生成 Service Worker 的插件。它基于 Workbox 库,能够帮助开发者轻松地为 PWA(Progressive Web App)添加离线支持和资源缓存功能。
2. 如何使用 workbox-webpack-plugin?
2.1 安装插件
首先,你需要通过 npm 或 yarn 安装 workbox-webpack-plugin:
npm install workbox-webpack-plugin --save-dev
或者
yarn add workbox-webpack-plugin --dev
2.2 配置 Webpack
在 Webpack 配置文件中引入 workbox-webpack-plugin,并将其添加到 plugins 数组中。你可以使用 GenerateSW 类来自动生成 Service Worker 文件。
// www.javascriptcn.com code example
const { GenerateSW } = require('workbox-webpack-plugin');
module.exports = {
// 其他 webpack 配置...
plugins: [
new GenerateSW({
clientsClaim: true,
skipWaiting: true,
runtimeCaching: [
{
urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
handler: 'CacheFirst',
options: {
cacheName: 'images',
expiration: {
maxEntries: 50,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 天
},
},
},
{
urlPattern: /\.(?:js|css)$/,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'static-resources',
},
},
],
}),
],
};2.3 配置选项
clientsClaim: true:Service Worker 在激活后立即控制所有客户端。skipWaiting: true:Service Worker 在安装后立即激活,跳过等待阶段。runtimeCaching:定义运行时缓存策略。每个缓存策略包括:urlPattern:匹配 URL 的正则表达式。handler:缓存策略,如CacheFirst、StaleWhileRevalidate等。options:缓存选项,如cacheName和expiration。
3. 运行 Webpack 构建
配置完成后,运行 Webpack 构建命令,workbox-webpack-plugin 会自动生成 Service Worker 文件,并将其注入到你的应用中。
npm run build
或者
yarn build
4. 注册 Service Worker
在应用的入口文件中注册生成的 Service Worker:
// www.javascriptcn.com code example
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
})
.catch(err => {
console.log('ServiceWorker registration failed: ', err);
});
});
}5. 测试离线功能
构建并部署应用后,你可以通过 Chrome DevTools 的 Application 面板来测试 Service Worker 的离线功能,确保资源能够正确缓存并在离线时可用。