Ir para o conteúdo principal
Version: 3.1.1

📦 plugin-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

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

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

Ter um worker de serviço instalado não é suficiente para fazer da sua aplicação um PWA. You'll need to at least include a Web App Manifest and have the correct tags in <head> (Options > pwaHead).

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

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

App installation support

Se seu navegador suporta isso, você deve ser capaz de instalar um site do Docusaurus como um aplicativo.

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.

note

App installation requires the HTTPS protocol and a valid manifest.

Offline mode (precaching)

Permite que os usuários navegue em um site do Docusaurus off-line, usando a predefinição do colaborador do serviço.

The workbox-precaching page explains the idea:

Uma das características dos workers do serviço é a capacidade de salvar um conjunto de arquivos no cache quando o trabalhador do serviço estiver instalando. Isso é frequentemente referido como "precurso", já que você está fazendo cache de conteúdo à frente do trabalhador do serviço sendo usado.

A principal razão para fazer isso é que ele dá aos desenvolvedores controle sobre o cache, significando que eles podem determinar quando e por quanto tempo um arquivo é armazenado em cache e também servi-lo para o navegador sem ir para a rede, o que significa que pode ser usado para criar aplicativos web que trabalham offline.

Caixa de trabalho leva muito do trabalho para fora do processo de perfuração, simplificando a API e garantindo que os ativos sejam baixados eficientemente.

Por padrão, o modo offline é ativado quando o site é instalado como um aplicativo. See the offlineModeActivationStrategies option for details.

Depois que o site for precedido, o trabalhador do serviço irá servir respostas em cache para visitas posteriores. Quando uma nova compilação é implantada junto com um novo funcionário, o novo vai começar a instalar e eventualmente passar para um estado de espera. Durante este estado de espera, um pop-up de recarga será exibido e pedirá ao usuário para recarregar a página para um novo conteúdo. 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.

warning

Modo Offline / precaching requer baixar todos os recursos estáticos do site antes do tempo, e pode consumir largura de banda desnecessária. Poderá não ser uma boa ideia activá-la para todo o tipo de sites.

Options

debug

  • Type: boolean
  • Default: false

Ativar modo depuração:

  • Registros de workbox
  • Logs adicionais do Docusaurus
  • Saída de arquivo SW não otimizada
  • Mapas de origem

offlineModeActivationStrategies

  • Type: ('appInstalled' | 'mobile' | 'saveData'| 'queryString' | 'always')[]
  • Default: ['appInstalled', 'queryString', 'standalone']

Estratégias usadas para ativar o modo offline em:

  • appInstalled: activates for users having installed the site as an app (not 100% reliable)
  • standalone: activates for users running the app as standalone (often the case once a PWA is installed)
  • queryString: activates if queryString contains offlineMode=true (convenient for PWA debugging)
  • mobile: activates for mobile users (width <= 996px)
  • saveData: activates for users with navigator.connection.saveData === true
  • always: activates for all users
warning

Use com cuidado: alguns usuários podem não gostar de ser forçados a usar o modo offline.

danger

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

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.

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

injectManifestConfig

Workbox options to pass to workbox.injectManifest(). Ele fornece controle sobre quais arquivos serão precedidos e disponíveis offline.

  • 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

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

Array of objects containing tagName and key-value pairs for attributes to inject into the <head> tag. Tecnicamente, você pode injetar qualquer tag head através disto, mas é idealmente usado para tags para tornar o PWA compatível com seu site. Aqui está uma lista de tags para tornar seu aplicativo totalmente compatível:

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

  • Type: string | undefined
  • Default: undefined

Útil para regras adicionais da caixa de trabalho. Você pode fazer tudo o que um service worker pode fazer aqui e usar todo o poder das bibliotecas da caixa de trabalho. O código foi transpilado, então você pode usar a sintaxe moderna ES6+ aqui.

Por exemplo, para armazenar em cache arquivos de rotas externas:

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());
}

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

swRegister

  • Type: string | false
  • Default: 'docusaurus-plugin-pwa/src/registerSW.js'

Adiciona uma entrada antes do aplicativo Docusaurus para que o registro possa acontecer antes que o aplicativo seja executado. The default registerSW.js file is enough for simple registration.

Passing false will disable registration entirely.

Manifest example

O manifesto do site Docusaurus pode servir como inspiração:

{
"name": "Docusaurus v2",
"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

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. Isso dirá ao service worker para instalar o service worker em espera e recarregar a página.

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;.

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