📦 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
- Yarn
- pnpm
- Bun
npm install --save @docusaurus/plugin-pwa
yarn add @docusaurus/plugin-pwa
pnpm add @docusaurus/plugin-pwa
bun add @docusaurus/plugin-pwa
Configuration
Create a PWA manifest at ./static/manifest.json
.
Modify docusaurus.config.js
with a minimal PWA config, like:
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
서비스 워커를 설치하는 것만으로 여러분의 애플리케이션이 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
여러분의 브라우저가 지원한다면 도큐사우루스 사이트를 앱처럼 설치할 수 있습니다.
앱 설치를 지원하려면 HTTPS 프로토콜을 사용해야 하며 유효한 매니페스트가 필요합니다.
Offline mode (precaching)
서비스 워커 사전캐싱을 사용해 도큐사우루스 사이트를 오프라인에서 사용자가 탐색할 수 있습니다.
The workbox-precaching page explains the idea:
서비스 워커의 기능 중 하나로 서비스 워커 설치 시 캐시 처리할 파일 묶음을 저장해놓을 수 있습니다. 서비스 워커가 사용되기 전에 콘텐츠를 캐시 처리하기 때문에 "사전캐싱"이라고 부릅니다.
이렇게 처리하는 이유는 개발자에게 캐시를 제어할 수 있는 권한을 주기 위함입니다. 개발자는 캐시를 언제 만들고 얼마나 오래 보관할지 결정할 수 있을 뿐 아니라 네트워크를 거치지 않고 브라우저에서 바로 서비스를 제공할 수 있습니다. 즉 오프라인에서 동작할 수 있는 웹 앱을 만들 수 있다는 겁니다.
Workbox는 API를 단순화하고 효율적으로 필요한 파일을 내려받을 수 있게 만들어 사전캐싱 작업을 쉽게 접근할 수 있도록 지원합니다.
기본적으로 오프라인 모드는 사이트가 앱으로 설치되면 활성화됩니다. See the offlineModeActivationStrategies
option for details.
사이트 사전캐싱 이후에 서비스 워커는 방문자에게 캐시된 응답을 제공합니다. 새로운 빌드가 새로운 서비스 워커와 함께 배포되면 새로운 앱이 설치되고 대기 상태로 이동하게 됩니다. 대기 상태에 들어가면 리로드 팝업이 표시되고 사용자에게 새로운 콘텐츠를 위해 페이지를 리로드할 것인지 물어봅니다. 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.
오프라인 모드나 사전캐싱은 사이트의 모든 애셋을 미리 내려받아야 하며 불필요한 대역폭을 사용할 수 있습니다. 모든 종류의 사이트에서 무조건 해당 기능을 활성화하는 건 좋은 생각은 아닙니다.
Options
debug
- Type:
boolean
- Default:
false
아래와 같은 디버그 모드를 설정합니다.
- Workbox 로그
- 추가적인 도큐사우루스 로그
- 최적화되지 못한 SW 파일 출력
- 소스맵
offlineModeActivationStrategies
- Type:
('appInstalled' | 'mobile' | 'saveData'| 'queryString' | 'always')[]
- Default:
['appInstalled', 'queryString', 'standalone']
오프라인 모드를 적용할 상태에 대한 옵션을 설정합니다.
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 containsofflineMode=true
(convenient for PWA debugging)mobile
: activates for mobile users (width <= 996px
)saveData
: activates for users withnavigator.connection.saveData === true
always
: activates for all users
주의해서 사용해주세요. 일부 사용자는 오프라인 모드로 사용하도록 강제되는 것을 싫어할 수도 있습니다.
페이지가 안정적인 형태로 PWA 렌더링을 처리했는지 여부를 확인할 수 없습니다.
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()
. 프리캐싱을 적용하고 오프라인에서 사용할 수 있는 애셋을 직접 설정할 수 있습니다.
- Type:
InjectManifestOptions
- Default:
{}
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. 기술적으로 어떤 head 태그 든 삽입할 수 있지만 여러분의 사이트 PWA에 적합한 태그를 사용하는 것이 이상적입니다. 아래 목록은 여러분의 앱에 적합한 태그 목록입니다.
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
Workbox에 적용할 규칙 추가 시 유용한 설정입니다. 서비스 워커의 모든 기능과 함께 Workbox 라이브러리의 강력한 추가 기능을 사용할 수 있습니다. 트랜스파일된 코드이며 최신 ES6+ 구문을 사용할 수 있습니다.
예를 들어 외부 경로에 있는 파일을 캐시하는 경우에는 아래와 같이 사용합니다.
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'
앱이 실행하기 전에 등록이 처리되도록 도큐사우루스 앱 앞에 항목을 추가합니다. The default registerSW.js
file is enough for simple registration.
Passing false
will disable registration entirely.
Manifest example
도큐사우루스 사이트 매니페스트를 참고하세요.
{
"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
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. 그리고 기다리고 있는 서비스 워커에게 설치를 진행하고 페이지를 리로드하도록 전달합니다.
The default theme includes an implementation for the reload popup and uses Infima Alerts.
Your component can render null
, but this is not recommended: users won't have a way to get up-to-date content.