Skip to main content
Version: 3.5.1

📦 plugin-pwa

Docusaurus 插件使用 工作箱 添加 PWA 支持。该插件仅在生产版本中生成 服务工作进程,并允许你创建完全符合 PWA 标准的文档站点,并提供离线和安装支持。

¥Docusaurus Plugin to add PWA support using Workbox. This plugin generates a Service Worker in production build only, and allows you to create fully PWA-compliant documentation site with offline and installation support.

安装

¥Installation

npm install --save @docusaurus/plugin-pwa

配置

¥Configuration

./static/manifest.json 创建 PWA 清单

¥Create a PWA manifest at ./static/manifest.json.

使用最小的 PWA 配置修改 docusaurus.config.js,例如:

¥Modify docusaurus.config.js with a minimal PWA config, like:

docusaurus.config.js
export default {
plugins: [
[
'@docusaurus/plugin-pwa',
{
debug: true,
offlineModeActivationStrategies: [
'appInstalled',
'standalone',
'queryString',
],
pwaHead: [
{
tagName: 'link',
rel: 'icon',
href: '/img/docusaurus.png',
},
{
tagName: 'link',
rel: 'manifest',
href: '/manifest.json', // your PWA manifest
},
{
tagName: 'meta',
name: 'theme-color',
content: 'rgb(37, 194, 160)',
},
],
},
],
],
};

渐进式网络应用

¥Progressive Web App

安装 Service Worker 不足以使你的应用成为 PWA。你至少需要包含 Web 应用清单 并在 <head> (选项 > pwaHead) 中包含正确的标签。

¥Having a service worker installed is not enough to make your application a PWA. You'll need to at least include a Web App Manifest and have the correct tags in <head> (Options > pwaHead).

部署后,你可以使用 Lighthouse 对你的站点运行审核。

¥After deployment, you can use Lighthouse to run an audit on your site.

有关你的网站成为 PWA 所需条件的更详尽列表,请参阅 渐进式应用清单

¥For a more exhaustive list of what it takes for your site to be a PWA, refer to the PWA Checklist

应用安装支持

¥App installation support

如果你的浏览器支持,你应该能够将 Docusaurus 网站安装为应用。

¥If your browser supports it, you should be able to install a Docusaurus site as an app.

A screen recording of the installation process. A button appears in the address bar of the browser, which displays a dialog asking &quot;install this application?&quot; when clicked. After clicking the &quot;Install&quot; button, a new application is opened in the operating system, opening to the Docusaurus homepage.

注意

应用安装需要 HTTPS 协议和有效的清单。

¥App installation requires the HTTPS protocol and a valid manifest.

离线模式(预缓存)

¥Offline mode (precaching)

我们通过使用 service-worker 预缓存使用户能够离线浏览 Docusaurus 站点。

¥We enable users to browse a Docusaurus site offline, by using service-worker precaching.

workbox-precaching 页面解释了这个想法:

¥The workbox-precaching page explains the idea:

Service Worker 的一个功能是能够在安装 Service Worker 时将一组文件保存到缓存中。这通常称为 "precaching",因为你在使用 Service Worker 之前缓存内容。

¥One feature of service workers is the ability to save a set of files to the cache when the service worker is installing. This is often referred to as "precaching", since you are caching content ahead of the service worker being used.

这样做的主要原因是它使开发者可以控制缓存,这意味着他们可以确定文件缓存的时间和时间,以及将其提供给浏览器而无需连接网络,这意味着它可以用于创建 Web 离线工作的应用。

¥The main reason for doing this is that it gives developers control over the cache, meaning they can determine when and how long a file is cached as well as serve it to the browser without going to the network, meaning it can be used to create web apps that work offline.

Workbox 通过简化 API 并确保有效下载资源,减轻了预缓存的大量繁重工作。

¥Workbox takes a lot of the heavy lifting out of precaching by simplifying the API and ensuring assets are downloaded efficiently.

默认情况下,当站点作为应用安装时,会启用离线模式。有关详细信息,请参阅 offlineModeActivationStrategies 选项。

¥By default, offline mode is enabled when the site is installed as an app. See the offlineModeActivationStrategies option for details.

预先缓存站点后,服务工作线程将为以后的访问提供缓存的响应。当新的构建与新的 Service Worker 一起部署时,新的 Service Worker 将开始安装并最终进入等待状态。在此等待状态期间,将显示重新加载弹出窗口并要求用户重新加载页面以获取新内容。在用户清除应用缓存或单击弹出窗口上的 reload 按钮之前,Service Worker 将继续提供旧内容。

¥After the site has been precached, the service worker will serve cached responses for later visits. When a new build is deployed along with a new service worker, the new one will begin installing and eventually move to a waiting state. During this waiting state, a reload popup will show and ask the user to reload the page for new content. Until the user either clears the application cache or clicks the reload button on the popup, the service worker will continue serving the old content.

警告

离线模式/预缓存需要提前下载站点的所有静态资源,并且会消耗不必要的带宽。对于所有类型的网站都激活它可能不是一个好主意。

¥Offline mode / precaching requires downloading all the static assets of the site ahead of time, and can consume unnecessary bandwidth. It may not be a good idea to activate it for all kind of sites.

选项

¥Options

debug

  • 类型:boolean

    ¥Type: boolean

  • 默认:false

    ¥Default: false

打开调试模式:

¥Turn debug mode on:

  • 工作箱日志

    ¥Workbox logs

  • 其他 Docusaurus 日志

    ¥Additional Docusaurus logs

  • 未优化的 SW 文件输出

    ¥Unoptimized SW file output

  • 源映射

    ¥Source maps

offlineModeActivationStrategies

  • 类型:('appInstalled' | 'mobile' | 'saveData'| 'queryString' | 'always')[]

    ¥Type: ('appInstalled' | 'mobile' | 'saveData'| 'queryString' | 'always')[]

  • 默认:['appInstalled', 'queryString', 'standalone']

    ¥Default: ['appInstalled', 'queryString', 'standalone']

用于打开离线模式的策略:

¥Strategies used to turn the offline mode on:

  • appInstalled:为已将网站安装为应用的用户激活(并非 100% 可靠)

    ¥appInstalled: activates for users having installed the site as an app (not 100% reliable)

  • standalone:为独立运行应用的用户激活(安装 PWA 后通常会出现这种情况)

    ¥standalone: activates for users running the app as standalone (often the case once a PWA is installed)

  • queryString:如果 queryString 包含 offlineMode=true 则激活(方便 PWA 调试)

    ¥queryString: activates if queryString contains offlineMode=true (convenient for PWA debugging)

  • mobile:为移动用户激活 (width <= 996px)

    ¥mobile: activates for mobile users (width <= 996px)

  • saveData:为 navigator.connection.saveData === true 的用户激活

    ¥saveData: activates for users with navigator.connection.saveData === true

  • always:为所有用户激活

    ¥always: activates for all users

警告

小心使用这个:有些用户可能不喜欢被迫使用离线模式。

¥Use this carefully: some users may not like to be forced to use the offline mode.

危险

无法以可靠的方式检测页面是否渲染为 PWA。

¥It is not possible to detect if a page is rendered as a PWA in a reliable manner.

appinstalled 事件已是 从规范中删除navigator.getInstalledRelatedApps() API 仅在最近的 Chrome 版本中受支持,并且需要在清单中声明 related_applications

¥The appinstalled event has been removed from the specification, and the navigator.getInstalledRelatedApps() API is only supported in recent Chrome versions and require related_applications declared in the manifest.

standalone 战略 是激活离线模式的一个很好的后备(至少在运行已安装的应用时)。

¥The standalone strategy is a nice fallback to activate the offline mode (at least when running the installed app).

injectManifestConfig

工作箱选项 传给 workbox.injectManifest()。这使你可以控制哪些资源将被预缓存并可以离线使用。

¥Workbox options to pass to workbox.injectManifest(). This gives you control over which assets will be precached, and be available offline.

  • 类型:InjectManifestOptions

    ¥Type: InjectManifestOptions

  • 默认:{}

    ¥Default: {}

docusaurus.config.js
export default {
plugins: [
[
'@docusaurus/plugin-pwa',
{
injectManifestConfig: {
manifestTransforms: [
//...
],
modifyURLPrefix: {
//...
},
// We already add regular static assets (HTML, images...) to be available offline
// You can add more files according to your needs
globPatterns: ['**/*.{pdf,docx,xlsx}'],
// ...
},
},
],
],
};

pwaHead

  • 类型:({ tagName: string; [attributeName: string]: string })[]

    ¥Type: ({ tagName: string; [attributeName: string]: string })[]

  • 默认:[]

    ¥Default: []

包含 tagName 和用于注入 <head> 标记的属性的键值对的对象数组。从技术上讲,你可以通过此注入任何头标签,但它最适合用于使你的网站 PWA 兼容的标签。以下是使你的应用完全兼容的标签列表:

¥Array of objects containing tagName and key-value pairs for attributes to inject into the <head> tag. Technically you can inject any head tag through this, but it's ideally used for tags to make your site PWA compliant. Here's a list of tag to make your app fully compliant:

export default {
plugins: [
[
'@docusaurus/plugin-pwa',
{
pwaHead: [
{
tagName: 'link',
rel: 'icon',
href: '/img/docusaurus.png',
},
{
tagName: 'link',
rel: 'manifest',
href: '/manifest.json',
},
{
tagName: 'meta',
name: 'theme-color',
content: 'rgb(37, 194, 160)',
},
{
tagName: 'meta',
name: 'apple-mobile-web-app-capable',
content: 'yes',
},
{
tagName: 'meta',
name: 'apple-mobile-web-app-status-bar-style',
content: '#000',
},
{
tagName: 'link',
rel: 'apple-touch-icon',
href: '/img/docusaurus.png',
},
{
tagName: 'link',
rel: 'mask-icon',
href: '/img/docusaurus.svg',
color: 'rgb(37, 194, 160)',
},
{
tagName: 'meta',
name: 'msapplication-TileImage',
content: '/img/docusaurus.png',
},
{
tagName: 'meta',
name: 'msapplication-TileColor',
content: '#000',
},
],
},
],
],
};

swCustom

  • 类型:string | undefined

    ¥Type: string | undefined

  • 默认:undefined

    ¥Default: undefined

对于其他 Workbox 规则很有用。你可以在这里执行 Service Worker 可以执行的任何操作,并使用工作箱库的全部功能。代码已转译,因此你可以在此处使用现代 ES6+ 语法。

¥Useful for additional Workbox rules. You can do whatever a service worker can do here, and use the full power of workbox libraries. The code is transpiled, so you can use modern ES6+ syntax here.

例如,要缓存来自外部路由的文件:

¥For example, to cache files from external routes:

import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';

// default fn export receiving some useful params
export default function swCustom(params) {
const {
debug, // :boolean
offlineMode, // :boolean
} = params;

// Cache responses from external resources
registerRoute((context) => {
return [
/graph\.facebook\.com\/.*\/picture/,
/netlify\.com\/img/,
/avatars1\.githubusercontent/,
].some((regex) => context.url.href.match(regex));
}, new StaleWhileRevalidate());
}

该模块应该有 default 函数导出,并接收一些参数。

¥The module should have a default function export, and receives some params.

swRegister

  • 类型:string | false

    ¥Type: string | false

  • 默认:'docusaurus-plugin-pwa/src/registerSW.js'

    ¥Default: 'docusaurus-plugin-pwa/src/registerSW.js'

在 Docusaurus 应用之前添加一个条目,以便可以在应用运行之前进行注册。默认的 registerSW.js 文件足以进行简单注册。

¥Adds an entry before the Docusaurus app so that registration can happen before the app runs. The default registerSW.js file is enough for simple registration.

通过 false 将完全禁用注册。

¥Passing false will disable registration entirely.

清单示例

¥Manifest example

Docusaurus 站点清单可以作为灵感:

¥The Docusaurus site manifest can serve as an inspiration:

{
"name": "Docusaurus",
"short_name": "Docusaurus",
"theme_color": "#2196f3",
"background_color": "#424242",
"display": "standalone",
"scope": "./",
"start_url": "./index.html",
"related_applications": [
{
"platform": "webapp",
"url": "https://docusaurus.io/manifest.json"
}
],
"icons": [
{
"src": "img/icons/icon-72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "img/icons/icon-96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "img/icons/icon-128x128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "img/icons/icon-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "img/icons/icon-152x152.png",
"sizes": "152x152",
"type": "image/png"
},
{
"src": "img/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "img/icons/icon-384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "img/icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}

自定义重新加载弹出窗口

¥Customizing reload popup

当新的 Service Worker 等待安装时,会渲染 @theme/PwaReloadPopup 组件,我们建议用户重新加载。你可以对该组件进行 swizzle 并实现你自己的 UI。它将接收 onReload 回调作为 props,当单击 reload 按钮时应该调用该回调。这将告诉服务工作线程安装等待的服务工作线程并重新加载页面。

¥The @theme/PwaReloadPopup component is rendered when a new service worker is waiting to be installed, and we suggest a reload to the user. You can swizzle this component and implement your own UI. It will receive an onReload callback as props, which should be called when the reload button is clicked. This will tell the service worker to install the waiting service worker and reload the page.

默认主题包括重新加载弹出窗口的实现并使用 Infima Alerts

¥The default theme includes an implementation for the reload popup and uses Infima Alerts.

A screen recording of the reload process. An alert box shows in the bottom right of the window, saying &quot;New content available&quot;. After clicking the &quot;Refresh&quot; button, the page&#39;s main heading changes from &quot;Introduction&quot; to &quot;PWA :))&quot;.

你的组件可以渲染 null,但不建议这样做:用户将无法获取最新内容。

¥Your component can render null, but this is not recommended: users won't have a way to get up-to-date content.