### Install @vite-pwa/sveltekit with pnpm
Source: https://vite-pwa-org.netlify.app/frameworks/sveltekit
Install the @vite-pwa/sveltekit plugin as a dev dependency using pnpm.
```bash
pnpm add -D @vite-pwa/sveltekit
```
--------------------------------
### Install @vite-pwa/sveltekit with npm
Source: https://vite-pwa-org.netlify.app/frameworks/sveltekit
Install the @vite-pwa/sveltekit plugin as a dev dependency using npm.
```bash
npm install -D @vite-pwa/sveltekit
```
--------------------------------
### Install @vite-pwa/sveltekit with yarn
Source: https://vite-pwa-org.netlify.app/frameworks/sveltekit
Install the @vite-pwa/sveltekit plugin as a dev dependency using yarn.
```bash
yarn add -D @vite-pwa/sveltekit
```
--------------------------------
### Build the plugin with PNPM
Source: https://vite-pwa-org.netlify.app/examples
Run these commands from the root of the cloned repository to install dependencies and build the plugin.
```shell
pnpm install
pnpm run build
```
--------------------------------
### Install vite-plugin-pwa with npm
Source: https://vite-pwa-org.netlify.app/guide
Install the vite-plugin-pwa package as a dev dependency using npm.
```bash
npm install -D vite-plugin-pwa
```
--------------------------------
### PWA Manifest Icon Configuration Example
Source: https://vite-pwa-org.netlify.app/guide/static-assets
Example of how to reference an image from the `src/assets` directory in your PWA Manifest. Ensure the image is also imported and used in your application's code.
```json
{
"src": "./src/assets/logo-192x192.png",
"sizes": "192x192",
"type": "image/png"
}
```
--------------------------------
### Install @vite-pwa/vitepress
Source: https://vite-pwa-org.netlify.app/frameworks/vitepress
Commands to install the required PWA package for VitePress.
```bash
pnpm add -D @vite-pwa/vitepress
```
```bash
yarn add -D @vite-pwa/vitepress
```
```bash
npm install -D @vite-pwa/vitepress
```
--------------------------------
### Install vite-plugin-pwa with pnpm
Source: https://vite-pwa-org.netlify.app/guide
Install the vite-plugin-pwa package as a dev dependency using pnpm.
```bash
pnpm add -D vite-plugin-pwa
```
--------------------------------
### Install @vite-pwa/astro
Source: https://vite-pwa-org.netlify.app/frameworks/astro
Install the @vite-pwa/astro package as a development dependency using your preferred package manager.
```bash
pnpm add -D @vite-pwa/astro
```
```bash
yarn add -D @vite-pwa/astro
```
```bash
npm install -D @vite-pwa/astro
```
--------------------------------
### Install @vite-pwa/assets-generator
Source: https://vite-pwa-org.netlify.app/assets-generator/integrations
Install the package as a dev dependency using your preferred package manager.
```bash
pnpm add -D @vite-pwa/assets-generator
```
```bash
yarn add -D @vite-pwa/assets-generator
```
```bash
npm install -D @vite-pwa/assets-generator
```
--------------------------------
### Install vite-plugin-pwa with yarn
Source: https://vite-pwa-org.netlify.app/guide
Install the vite-plugin-pwa package as a dev dependency using yarn.
```bash
yarn add -D vite-plugin-pwa
```
--------------------------------
### Preview Nuxt 3 PWA Build
Source: https://vite-pwa-org.netlify.app/examples/nuxt
Commands to build and start the Nuxt server for PWA testing.
```shell
nr dev:preview:build
```
```shell
nr dev:preview:generate
```
--------------------------------
### Install Vite PWA Plugin from PR
Source: https://vite-pwa-org.netlify.app/guide/change-log
Use these commands to install a specific version of the plugin from a pull request using the pkg-pr-new service.
```bash
pnpm add -D https://pkg.pr.new/vite-plugin-pwa@88b2e45
```
```bash
yarn add -D https://pkg.pr.new/vite-plugin-pwa@88b2e45
```
```bash
npm i -D https://pkg.pr.new/vite-plugin-pwa@88b2e45
```
--------------------------------
### Install @vite-pwa/remix
Source: https://vite-pwa-org.netlify.app/frameworks/remix
Commands to add the Remix PWA module as a development dependency.
```bash
pnpm add -D @vite-pwa/remix
```
```bash
yarn add -D @vite-pwa/remix
```
```bash
npm install -D @vite-pwa/remix
```
--------------------------------
### Install @vite-pwa/assets-generator with pnpm
Source: https://vite-pwa-org.netlify.app/assets-generator/api
Install the @vite-pwa/assets-generator package as a dev dependency using pnpm.
```bash
pnpm add -D @vite-pwa/assets-generator
```
--------------------------------
### Install @vite-pwa/assets-generator with npm
Source: https://vite-pwa-org.netlify.app/assets-generator/api
Install the @vite-pwa/assets-generator package as a dev dependency using npm.
```bash
npm install -D @vite-pwa/assets-generator
```
--------------------------------
### Install @vite-pwa/assets-generator with yarn
Source: https://vite-pwa-org.netlify.app/assets-generator/api
Install the @vite-pwa/assets-generator package as a dev dependency using yarn.
```bash
yarn add -D @vite-pwa/assets-generator
```
--------------------------------
### Install PNPM globally
Source: https://vite-pwa-org.netlify.app/examples
Use this command to install the PNPM package manager if it is not already available on your system.
```shell
npm install -g pnpm
```
--------------------------------
### Define Custom Configuration with pwa-assets.config.js
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Create a configuration file to customize PWA assets generation. This example uses the minimal-2023 preset and specifies the source images.
```typescript
import {
defineConfig,
minimal2023Preset as preset
} from '@vite-pwa/assets-generator/config'
export default defineConfig({
headLinkOptions: {
preset: '2023'
},
preset,
images: ['public/logo.svg']
})
```
--------------------------------
### Configure Vite for Remix PWA
Source: https://vite-pwa-org.netlify.app/frameworks/remix
Setup the Remix PWA preset and plugin within the vite.config.js file.
```typescript
// vite.config.js
import { vitePlugin as remix } from '@remix-run/dev'
import { installGlobals } from '@remix-run/node'
import { defineConfig } from 'vite'
import { RemixVitePWA } from '@vite-pwa/remix'
installGlobals()
const { RemixVitePWAPlugin, RemixPWAPreset } = RemixVitePWA()
export default defineConfig({
plugins: [
remix({
presets: [RemixPWAPreset()],
}),
RemixVitePWAPlugin({
// PWA options
})
]
})
```
--------------------------------
### Laravel PWA Build Commands
Source: https://vite-pwa-org.netlify.app/frameworks/laravel
Standard commands to clone the repository, install dependencies, and build the project for PWA functionality.
```bash
git clone git@github.com:sfreytag/laravel-vite-pwa.git
cd laravel-vite-pwa
composer install
cp .env.example .env
php artisan key:generate
npm install
npm run build
```
--------------------------------
### Install @vite-pwa/nuxt module
Source: https://vite-pwa-org.netlify.app/frameworks/nuxt
Use this command to add the PWA module to your Nuxt 3 project.
```shell
npx nuxi@latest module add @vite-pwa/nuxt
```
--------------------------------
### Combine Preset and Splash Screens with combinePresetAndAppleSplashScreens
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Integrate splash screen configurations with existing presets using `combinePresetAndAppleSplashScreens`. This example merges `minimal2023Preset` with custom splash screen options for 'iPad Air 9.7"'. The `log: true` option in `linkMediaOptions` is useful for debugging.
```typescript
import {
combinePresetAndAppleSplashScreens,
defineConfig,
minimal2023Preset
} from '@vite-pwa/assets-generator/config'
export default defineConfig({
headLinkOptions: {
preset: '2023'
},
preset: combinePresetAndAppleSplashScreens(
minimal2023Preset,
{
padding: 0.3,
resizeOptions: { background: 'white', fit: 'contain' },
// by default, dark splash screens are exluded
// darkResizeOptions: { background: 'black' },
linkMediaOptions: {
// will log the links you need to add to your html pages
log: true,
// add screen to media attribute link?
// by default:
//
addMediaScreen: true,
basePath: '/',
// add closing link tag?
// by default:
//
// with xhtml enabled:
//
xhtml: false
},
png: {
compressionLevel: 9,
quality: 60
},
name: (landscape, size, dark) => {
return `apple-splash-${landscape ? 'landscape' : 'portrait'}-${typeof dark === 'boolean' ? (dark ? 'dark-' : 'light-') : ''}${size.width}x${size.height}.png`
}
},
['iPad Air 9.7"']
),
images: ['public/logo.svg']
})
```
--------------------------------
### Configure favicon generation
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Example configuration for generating specific favicon sizes alongside PWA icons.
```ts
import { defineConfig } from '@vite-pwa/assets-generator/config'
export default defineConfig({
/* remember to include the preset for favicons and apple touch icon */
headLinkOptions: {
preset: '2023'
},
preset: {
transparent: {
sizes: [64, 192, 512],
favicons: [[48, 'favicon-48x48.ico'], [64, 'favicon.ico']]
},
maskable: {
sizes: [512]
},
apple: {
sizes: [180]
}
},
images: ['public/logo.svg'],
})
```
--------------------------------
### Configuring navigateFallbackAllowlist for generateSW
Source: https://vite-pwa-org.netlify.app/guide/development
Example of how to configure `navigateFallbackAllowlist` within `devOptions` to manage service worker interception.
```APIDOC
## Configure navigateFallbackAllowlist for generateSW
### Description
If your pages/routes are being intercepted by the service worker in development and causing issues, you can use `navigateFallbackAllowlist` to specify which routes the service worker should intercept. This example shows how to configure it to only allow interception of `index.html`.
### Method
Configuration
### Endpoint
N/A
### Parameters
#### Request Body
- **devOptions.navigateFallbackAllowlist** (RegExp[]) - Required - An array of regular expressions defining the routes the service worker is allowed to intercept.
### Request Example
```typescript
import { defineConfig } from 'vite'
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
VitePWA({
/* other options */
devOptions: {
navigateFallbackAllowlist: [/^index.html$/]
/* other options */
}
})
]
})
```
### Response
N/A
```
--------------------------------
### Configure custom PNG optimization
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Example of overriding default PNG compression settings in the configuration file.
```ts
import {
defineConfig,
minimal2023Preset
} from '@vite-pwa/assets-generator/config'
export default defineConfig({
headLinkOptions: {
preset: '2023'
},
preset: {
...minimal2023Preset,
png: {
compressionLevel: 9,
quality: 85
}
},
images: ['public/logo.svg']
})
```
--------------------------------
### ReloadPrompt Component Example
Source: https://vite-pwa-org.netlify.app/frameworks/react
A sample React component `ReloadPrompt.tsx` demonstrating how to use the `useRegisterSW` hook to inform the user about offline readiness and new content availability, providing options to reload or close the prompt.
```APIDOC
## ReloadPrompt Component
### Description
A reusable React component that displays a toast notification to the user when the app is ready offline or when a new version of the service worker is available, offering options to reload or dismiss.
### Usage
Import and use the `ReloadPrompt` component in your React application.
```tsx
import React from 'react';
import './ReloadPrompt.css';
import { useRegisterSW } from 'virtual:pwa-register/react';
function ReloadPrompt() {
const {
offlineReady: [offlineReady, setOfflineReady],
needRefresh: [needRefresh, setNeedRefresh],
updateServiceWorker,
} = useRegisterSW({
onRegistered(r) {
console.log('SW Registered: ' + r);
},
onRegisterError(error) {
console.log('SW registration error', error);
},
});
const close = () => {
setOfflineReady(false);
setNeedRefresh(false);
};
return (
{ (offlineReady || needRefresh) &&
{ offlineReady
? App ready to work offline
: New content available, click on reload button to update.
}
{ needRefresh && }
}
);
}
export default ReloadPrompt;
```
### CSS Styles
Refer to the `ReloadPrompt.css` file for styling details.
```
--------------------------------
### Configure globPatterns for injectManifest
Source: https://vite-pwa-org.netlify.app/guide/static-assets
Example of configuring `globPatterns` for the `injectManifest` strategy. This allows `workbox-build` to match files in the `dist` folder based on the provided patterns.
```typescript
VitePWA({
injectManifest: {
globPatterns: ['**/*.{js,css,html}']
}
})
```
--------------------------------
### Configure pwaAssets in vite-plugin-pwa
Source: https://vite-pwa-org.netlify.app/assets-generator/integrations
Enable the experimental pwaAssets feature by configuring the `pwaAssets` option within your vite-plugin-pwa setup. This can be done using an inlined preset or an external configuration file.
```typescript
import { defineConfig } from 'vite'
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
VitePWA({
// other pwa options
// pwa assets
pwaAssets: {
// options
}
})
]
})
```
--------------------------------
### Configure globPatterns for generateSW
Source: https://vite-pwa-org.netlify.app/guide/static-assets
Example of configuring `globPatterns` for the `generateSW` strategy within the `workbox` option. This ensures specific file types are included in the service worker precache.
```typescript
VitePWA({
workbox: {
globPatterns: ['**/*.{js,css,html}']
}
})
```
--------------------------------
### Override PNG output names
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Example of providing a custom assetName function within the configuration file.
```ts
import {
defineConfig,
minimal2023Preset
} from '@vite-pwa/assets-generator/config'
export default defineConfig({
headLinkOptions: {
preset: '2023'
},
preset: {
...minimal2023Preset,
assetName: (type: AssetType, size: ResolvedAssetSize) => {
/* your logic here */
}
},
images: ['public/logo.svg']
})
```
--------------------------------
### Configure iOS Splash Screens with createAppleSplashScreens
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Use `createAppleSplashScreens` to define splash screen configurations for specific iOS devices. This example configures splash screens for 'iPad Air 9.7"' with custom padding, resize options, and naming conventions. Ensure `log: true` is set to see the generated HTML links.
```typescript
import {
createAppleSplashScreens,
defineConfig,
minimal2023Preset
} from '@vite-pwa/assets-generator/config'
export default defineConfig({
headLinkOptions: {
preset: '2023'
},
preset: {
...minimal2023Preset,
appleSplashScreens: createAppleSplashScreens({
padding: 0.3,
resizeOptions: { background: 'white', fit: 'contain' },
// by default, dark splash screens are exluded
// darkResizeOptions: { background: 'black' },
linkMediaOptions: {
// will log the links you need to add to your html pages
log: true,
// add screen to media attribute link?
// by default:
//
addMediaScreen: true,
basePath: '/',
// add closing link tag?
// by default:
//
// with xhtml enabled:
//
xhtml: false
},
png: {
compressionLevel: 9,
quality: 60
},
name: (landscape, size, dark) => {
return `apple-splash-${landscape ? 'landscape' : 'portrait'}-${typeof dark === 'boolean' ? (dark ? 'dark-' : 'light-') : ''}${size.width}x${size.height}.png`
}
}, ['iPad Air 9.7"'])
},
images: ['public/logo.svg']
})
```
--------------------------------
### Run CLI with Configuration File
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
After setting up the configuration file, you can run the CLI without arguments to use the defined settings.
```bash
$ pwa-assets-generator
```
--------------------------------
### Basic netlify.toml deployment configuration
Source: https://vite-pwa-org.netlify.app/deployment/netlify
Complete configuration for build settings, SPA redirects, and header rules in a single netlify.toml file.
```toml
[build]
publish = "dist"
command = "pnpm run build"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[[headers]]
for = "/manifest.webmanifest"
[headers.values]
Content-Type = "application/manifest+json"
[[headers]]
for = "/assets/*"
[headers.values]
cache-control = '''
max-age=31536000,
immutable
'''
```
--------------------------------
### Configure HTML Entry Point for PWA
Source: https://vite-pwa-org.netlify.app/guide/pwa-minimal-requirements
Include these meta and link tags in the section of your index.html to satisfy basic PWA requirements.
```html
My Awesome App
```
--------------------------------
### Build the plugin with Yarn
Source: https://vite-pwa-org.netlify.app/examples
Alternative commands for building the plugin using the Yarn package manager.
```shell
yarn && yarn build
```
--------------------------------
### Basic CLI Usage
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Generate PWA assets using the CLI by specifying a preset and the source image. The source files should be relative to the project root.
```bash
$ pwa-assets-generator [options] [sources]
```
```bash
$ pwa-assets-generator --preset minimal-2023 public/logo.svg
```
--------------------------------
### Run VitePress Preview
Source: https://vite-pwa-org.netlify.app/examples/vitepress
Execute this script from your shell in the root folder to run the VitePress site locally.
```shell
pnpm run preview
```
--------------------------------
### VitePress Theme Setup for Reload Prompt
Source: https://vite-pwa-org.netlify.app/frameworks/vitepress
Integrates the `ReloadPrompt` component into the VitePress layout to display update notifications. This setup requires the `ReloadPrompt.vue` component to be available.
```typescript
import { h } from 'vue'
import Theme from 'vitepress/theme'
import ReloadPrompt from './components/ReloadPrompt.vue'
export default {
...Theme,
Layout() {
return h(Theme.Layout, null, {
'layout-bottom': () => h(ReloadPrompt)
})
}
}
```
--------------------------------
### Build PWA for Production
Source: https://vite-pwa-org.netlify.app/frameworks/laravel
Run this command to build the PWA for production. This ensures the PWA offline cache does not interfere with development cycles.
```bash
npm run build
```
--------------------------------
### Register service worker for auto-update
Source: https://vite-pwa-org.netlify.app/frameworks
Example of registering the service worker with an onOfflineReady callback for auto-update mode.
```typescript
import { registerSW } from 'virtual:pwa-register'
const updateSW = registerSW({
onOfflineReady() {}
})
```
--------------------------------
### Using PWA Manifest Components
Source: https://vite-pwa-org.netlify.app/frameworks/nuxt
Demonstrates how to include VitePwaManifest or NuxtPwaManifest components in your `app.vue` to automatically inject the web manifest link into your HTML pages.
```APIDOC
## Using VitePwaManifest/NuxtPwaManifest in app.vue
### Description
Adding either the `VitePwaManifest` or `NuxtPwaManifest` component to your root `app.vue` file will automatically inject the necessary web manifest link into the `` section of your HTML pages.
### Usage
**Option 1: Using `VitePwaManifest`**
```vue
```
**Option 2: Using `NuxtPwaManifest`**
```vue
```
### Resulting HTML
After including the component, your HTML's `` will contain a link to the web manifest:
```html
```
```
--------------------------------
### Configure Web App Manifest in Vite
Source: https://vite-pwa-org.netlify.app/guide/pwa-minimal-requirements
Define the manifest object within the VitePWA plugin options to ensure your application is installable.
```ts
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
VitePWA({
includeAssets: ['favicon.ico', 'apple-touch-icon.png', 'mask-icon.svg'],
manifest: {
name: 'My Awesome App',
short_name: 'MyApp',
description: 'My Awesome App description',
theme_color: '#ffffff',
icons: [
{
src: 'pwa-192x192.png',
sizes: '192x192',
type: 'image/png'
},
{
src: 'pwa-512x512.png',
sizes: '512x512',
type: 'image/png'
}
]
}
})
]
})
```
--------------------------------
### Configuration Options
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Details on how to configure the PWA assets generator using the defineConfig utility.
```APIDOC
## Configuration Options
### Description
Configure the PWA assets generator using the `defineConfig` function. This allows customization of head links, asset naming, padding, and PNG optimization.
### Request Body
- **headLinkOptions** (object) - Optional - Configuration for favicon and apple touch icon links.
- **basePath** (string) - Optional - Base path for head links (default: '/').
- **preset** (string) - Optional - Preset to use ('default' or '2023').
- **resolveSvgName** (function) - Optional - Function to resolve SVG icon names.
- **preset** (object) - Optional - Custom preset configuration for assets.
- **assetName** (function) - Optional - Custom function to define PNG output names.
- **png** (object) - Optional - Sharp PNG output options (compressionLevel, quality).
- **transparent/maskable/apple** (object) - Optional - Asset type specific settings (sizes, padding, favicons).
- **images** (array) - Required - List of image source paths.
- **manifestIconsEntry** (boolean) - Optional - Enable or disable PWA manifest icons entry logging (default: true).
### Request Example
```ts
import { defineConfig, minimal2023Preset } from '@vite-pwa/assets-generator/config'
export default defineConfig({
headLinkOptions: {
preset: '2023'
},
preset: {
...minimal2023Preset,
png: {
compressionLevel: 9,
quality: 85
}
},
images: ['public/logo.svg']
})
```
```
--------------------------------
### Vue 3 Periodic Service Worker Updates
Source: https://vite-pwa-org.netlify.app/frameworks/vue
Configure periodic service worker checks using `useRegisterSW` with a specified interval in milliseconds. The example checks every hour.
```typescript
import { useRegisterSW } from 'virtual:pwa-register/vue'
const intervalMS = 60 * 60 * 1000
const updateServiceWorker = useRegisterSW({
onRegistered(r) {
r && setInterval(() => {
r.update()
}, intervalMS)
}
})
```
--------------------------------
### Configure Assets Generation in package.json (using config file)
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Define a script in your package.json to run the PWA assets generator, which will utilize the project's configuration file.
```json
{
"scripts": {
"generate-pwa-assets": "pwa-assets-generator"
}
}
```
--------------------------------
### Server.php for Local Development Service Worker
Source: https://vite-pwa-org.netlify.app/frameworks/laravel
Configuration in `server.php` to serve the `sw.js` file and provide the `Service-Worker-Allowed` header for local development with `php artisan serve`.
```php
singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
});
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = tap($kernel->handle(
$request = Request::capture()
))->send();
$kernel->terminate($request, $response);
// Add Service-Worker-Allowed header for local development
if (str_ends_with($request->getPathInfo(), '/sw.js')) {
header('Service-Worker-Allowed: /');
}
```
--------------------------------
### Preact Periodic Service Worker Updates
Source: https://vite-pwa-org.netlify.app/frameworks/preact
Configure periodic service worker updates in a Preact application using the `useRegisterSW` hook. The example checks for updates every hour.
```typescript
import { useRegisterSW } from 'virtual:pwa-register/preact'
const intervalMS = 60 * 60 * 1000
const updateServiceWorker = useRegisterSW({
onRegistered(r) {
r && setInterval(() => {
r.update()
}, intervalMS)
}
})
```
--------------------------------
### PWA Injection Interface (TypeScript)
Source: https://vite-pwa-org.netlify.app/frameworks/nuxt
Defines the PWA injection interface used in Nuxt applications, including properties for PWA installation status, prompt visibility, service worker activation, and update handling.
```APIDOC
## TypeScript Interface: PwaInjection
### Description
This interface defines the structure of the PWA injection object available in Nuxt applications. It provides methods and reactive properties to interact with the PWA features.
### Properties
- **isInstalled** (boolean) - Deprecated: use `isPWAInstalled` instead.
- **isPWAInstalled** (Ref) - Reactive reference indicating if the PWA is installed.
- **showInstallPrompt** (Ref) - Reactive reference indicating if the install prompt should be shown.
- **swActivated** (Ref) - Reactive reference indicating if the service worker is activated.
- **registrationError** (Ref) - Reactive reference indicating if there was an error during service worker registration.
- **offlineReady** (Ref) - Reactive reference indicating if the application is ready for offline use.
- **needRefresh** (Ref) - Reactive reference indicating if a new version of the PWA is available and needs a refresh.
### Methods
- **cancelInstall** - () => void - Cancels the PWA installation process.
- **install** - () => Promise - Initiates the PWA installation.
- **updateServiceWorker** - (reloadPage?: boolean | undefined) => Promise - Updates the service worker, optionally reloading the page.
- **cancelPrompt** - () => Promise - Cancels the install prompt.
- **getSWRegistration** - () => ServiceWorkerRegistration | undefined - Returns the service worker registration object if available.
### Nuxt App Injection
```typescript
declare module '#app' {
interface NuxtApp {
$pwa: UnwrapNestedRefs
}
}
```
```
--------------------------------
### Configure SvelteKit PWA Plugin
Source: https://vite-pwa-org.netlify.app/frameworks/sveltekit
Update the Vite configuration file to include the SvelteKitPWA plugin.
```js
// vite.config.js / vite.config.ts
import { SvelteKitPWA } from '@vite-pwa/sveltekit'
/** @type {import('vite').UserConfig} */
const config = {
plugins: [
sveltekit(),
SvelteKitPWA({/* pwa options */})
],
}
export default config
```
--------------------------------
### Register Service Worker with Periodic Updates
Source: https://vite-pwa-org.netlify.app/guide/periodic-sw-updates
Use this snippet to register a service worker and set an interval for checking updates. The interval is in milliseconds; the example checks every hour. Ensure `virtual:pwa-register` is imported.
```typescript
import { registerSW } from 'virtual:pwa-register'
const intervalMS = 60 * 60 * 1000
const updateSW = registerSW({
onRegistered(r) {
r && setInterval(() => {
r.update()
}, intervalMS)
}
})
```
--------------------------------
### Generate Dark Splash Screens
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
To generate dark splash screens, provide `darkResizeOptions`. This example shows how to enable dark splash screens with a black background, which is the default, or a custom background color. This configuration is used in conjunction with `combinePresetAndAppleSplashScreens`.
```typescript
import {
combinePresetAndAppleSplashScreens,
defineConfig,
minimal2023Preset
} from '@vite-pwa/assets-generator/config'
export default defineConfig({
headLinkOptions: {
preset: '2023'
},
preset: combinePresetAndAppleSplashScreens(minimal2023Preset, {
// dark splash screens using black background (the default)
darkResizeOptions: { background: 'black', fit: 'contain' },
// or using a custom background color
// darkResizeOptions: { background: '#1f1f1f' },
}, ['iPad Air 9.7"']),
images: ['public/logo.svg']
})
```
--------------------------------
### Use Manifest Icon via Static Import
Source: https://vite-pwa-org.netlify.app/guide/static-assets
Demonstrates how to use a PWA manifest icon referenced from `src/assets` by statically importing it into your JavaScript/TypeScript module.
```javascript
// src/main.js or src/main.ts
// can be any js/ts/jsx/tsx module or single file component
import logo from './assets/logo-192x192.png'
document.getElementById('logo-img').src = logo
```
--------------------------------
### Custom Service Worker for Network First Strategy
Source: https://vite-pwa-org.netlify.app/workbox/inject-manifest
Implement a custom service worker using Workbox for the Network First strategy. Includes logic for cache management, fallback routes, and client claiming. Ensure Workbox dependencies are installed as dev dependencies.
```typescript
import type { ManifestEntry } from 'workbox-build'
import type { StrategyHandler } from 'workbox-strategies'
import { cacheNames, clientsClaim } from 'workbox-core'
import { registerRoute, setCatchHandler, setDefaultHandler } from 'workbox-routing'
import {
NetworkFirst,
NetworkOnly,
Strategy
} from 'workbox-strategies'
// Give TypeScript the correct global.
declare let self: ServiceWorkerGlobalScope
declare type ExtendableEvent = any
const data = {
race: false,
debug: false,
credentials: 'same-origin',
networkTimeoutSeconds: 0,
fallback: 'index.html'
}
const cacheName = cacheNames.runtime
function buildStrategy(): Strategy {
if (race) {
class CacheNetworkRace extends Strategy {
_handle(request: Request, handler: StrategyHandler): Promise {
const fetchAndCachePutDone: Promise = handler.fetchAndCachePut(request)
const cacheMatchDone: Promise = handler.cacheMatch(request)
return new Promise((resolve, reject) => {
fetchAndCachePutDone.then(resolve).catch((e) => {
if (debug)
console.log(`Cannot fetch resource: ${request.url}`, e)
})
cacheMatchDone.then(response => response && resolve(response))
// Reject if both network and cache error or find no response.
Promise.allSettled([fetchAndCachePutDone, cacheMatchDone]).then((results) => {
const [fetchAndCachePutResult, cacheMatchResult] = results
if (fetchAndCachePutResult.status === 'rejected' && !cacheMatchResult.value)
reject(fetchAndCachePutResult.reason)
})
})
}
}
return new CacheNetworkRace()
}
else {
if (networkTimeoutSeconds > 0)
return new NetworkFirst({ cacheName, networkTimeoutSeconds })
else
return new NetworkFirst({ cacheName })
}
}
const manifest = self.__WB_MANIFEST as Array
const cacheEntries: RequestInfo[] = []
const manifestURLs = manifest.map(
(entry) => {
const url = new URL(entry.url, self.location)
cacheEntries.push(new Request(url.href, {
credentials: credentials as any
}))
return url.href
}
)
self.addEventListener('install', (event: ExtendableEvent) => {
event.waitUntil(
caches.open(cacheName).then((cache) => {
return cache.addAll(cacheEntries)
})
)
})
self.addEventListener('activate', (event: ExtendableEvent) => {
// - clean up outdated runtime cache
event.waitUntil(
caches.open(cacheName).then((cache) => {
// clean up those who are not listed in manifestURLs
cache.keys().then((keys) => {
keys.forEach((request) => {
debug && console.log(`Checking cache entry to be removed: ${request.url}`)
if (!manifestURLs.includes(request.url)) {
cache.delete(request).then((deleted) => {
if (debug) {
if (deleted)
console.log(`Precached data removed: ${request.url || request}`)
else
console.log(`No precache found: ${request.url || request}`)
}
})
}
})
})
})
)
})
registerRoute(
({ url }) => manifestURLs.includes(url.href),
buildStrategy()
)
setDefaultHandler(new NetworkOnly())
// fallback to app-shell for document request
setCatchHandler(({ event }): Promise => {
switch (event.request.destination) {
case 'document':
return caches.match(fallback).then((r) => {
return r ? Promise.resolve(r) : Promise.resolve(Response.error())
})
default:
return Promise.resolve(Response.error())
}
})
// this is necessary, since the new service worker will keep on skipWaiting state
// and then, caches will not be cleared since it is not activated
self.skipWaiting()
clientsClaim()
```
--------------------------------
### Import PWA Options from Module
Source: https://vite-pwa-org.netlify.app/frameworks/remix
Alternative method to import PWA options directly from the package.
```typescript
import {
cleanupOutdatedCaches,
clientsClaimMode,
enablePrecaching,
navigateFallback,
promptForUpdate,
staticRoutes,
dynamicRoutes,
routes,
ssr,
} from '@vite-pwa/remix/sw'
```
--------------------------------
### Define custom preset with padding
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Demonstrates how to create a custom preset that overrides default padding values for different asset types.
```ts
import type { Preset } from '@vite-pwa/assets-generator/config';
export const minimalPresetNoPadding: Preset = {
transparent: {
sizes: [64, 192, 512],
favicons: [[48, 'favicon.ico']],
padding: 0
},
maskable: {
sizes: [512],
padding: 0
},
apple: {
sizes: [180],
padding: 0
}
}
```
--------------------------------
### Custom Apple Splash Screen Configuration
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Configure custom splash screens for specific Apple devices, overriding global settings for padding, dark mode background, and naming conventions. This example demonstrates generating dark splash screens with a global padding of 0.5 and a dark background of '#1f1f1f', while applying custom settings for 'iPhone 6' including padding of 0.4 and a dark background of '#2f2f2f'.
```typescript
import type {
AppleDeviceName,
AppleDeviceSize,
} from '@vite-pwa/assets-generator/config'
import {
appleSplashScreenSizes,
defineConfig,
minimal2023Preset
} from '@vite-pwa/assets-generator/config'
const devices: AppleDeviceName[] = ['iPad Air 9.7"', 'iPhone 6']
function createCustomAppleSplashScreens(
options: {
padding?: number
resizeOptions?: ResizeOptions
darkResizeOptions?: ResizeOptions
linkMediaOptions?: AppleTouchStartupImageOptions
name?: AppleSplashScreenName
} = {}
) {
const {
padding,
resizeOptions,
darkResizeOptions,
linkMediaOptions,
name,
} = options
return {
sizes: devices.map((deviceName) => {
const size = appleSplashScreenSizes[deviceName]
if (deviceName === 'iPhone 6') {
return {
size: { ...size, padding: 0.4 },
darkResizeOptions: { background: '#2f2f2f' },
name: (landscape, size, dark) => `iphone6-${landscape ? 'landscape' : 'portrait'}${dark ? '-dark' : ''}.png`
}
}
return size
}),
padding,
resizeOptions,
darkResizeOptions,
linkMediaOptions,
name,
}
}
export default defineConfig({
headLinkOptions: {
preset: '2023'
},
preset: {
...minimal2023Preset,
appleSplashScreens: createCustomAppleSplashScreens({
padding: 0.5,
darkResizeOptions: { background: '#1f1f1f' },
})
},
images: ['public/logo.svg']
})
```
--------------------------------
### Enable Experimental includeAllowlist in VitePress PWA Config
Source: https://vite-pwa-org.netlify.app/frameworks/vitepress
Configures Vite PWA to use the `generateSW` strategy and enables the experimental `includeAllowlist` option. This requires VitePress `1.0.0-rc.14+` and a server configuration to return 404 for non-existent pages.
```typescript
// .vitepress/config.ts
import { defineConfig } from 'vitepress'
import { withPwa } from '@vite-pwa/vitepress'
export default withPwa(defineConfig({
/* your VitePress options */
/* Vite PWA Options */
pwa: {
strategies: 'generateSW', // <== if omitted, defaults to `generateSW`
workbox: { /* your workbox configuration if any */ },
experimental: {
includeAllowlist: true
}
}
}))
```
--------------------------------
### HTML Head Entries for Preset Minimal
Source: https://vite-pwa-org.netlify.app/assets-generator
Add these links to your HTML head when using the Preset Minimal configuration. This handles favicon and apple touch icon requirements.
```html
```
--------------------------------
### Basic Apache Configuration with HTTP to HTTPS Redirection
Source: https://vite-pwa-org.netlify.app/deployment/apache
This configuration sets up Apache to listen on port 80, serve content from a specified DocumentRoot, and redirect all HTTP traffic to HTTPS. Ensure to replace placeholders with your actual server details.
```apache
# httpd.conf
ServerRoot ""
Listen 80
ServerName www.yourdomain.com
DocumentRoot ""
# modules
LoadModule mime_module modules/mod_mime.so
LoadModule rewrite_module modules/mod_rewrite.so
# mime types
# Manifest file
AddType application/manifest+json webmanifest
# your https configuration
Include conf/extra/https-www.yourdomain.com.conf
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
ServerName www.yourdomain.com
RewriteEngine On
# disable TRACE and TRACK methods
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]
Options +FollowSymlinks
RewriteCond %{SERVER_PORT} !443
RewriteRule (.*) https://www.yourdomain.com/ [L,R]
ErrorLog logs/www.yourdomain.com-error_log
CustomLog logs/www.yourdomain.com-access_log combined
```
--------------------------------
### Register Default Service Worker Implementation
Source: https://vite-pwa-org.netlify.app/frameworks/remix
Use the setupPwa helper to register default Workbox recipes in the service worker.
```typescript
import { setupPwa } from '@vite-pwa/remix/sw'
setupPwa({ manifest: self.__WB_MANIFEST })
```
--------------------------------
### Configure Vite and SvelteKitPWA Plugin
Source: https://vite-pwa-org.netlify.app/frameworks/sveltekit
Configure Vite to use the sveltekit() plugin and the SvelteKitPWA plugin, specifying the custom service worker filename and source directory.
```javascript
// vite.config.js or vite.config.ts
/** @type {import('vite').UserConfig} */
const config = {
plugins: [
sveltekit(),
SvelteKitPWA({
strategies: 'injectManifest',
srcDir: 'src',
filename: 'my-sw.js', // or `my-sw.ts`
/* other pwa options */
})
],
};
export default config;
```
--------------------------------
### Import PWA Virtual Module in Astro Layout
Source: https://vite-pwa-org.netlify.app/frameworks/astro
Import the 'virtual:pwa-info' module in your main Astro layout to enable PWA features. This is necessary because Astro does not inject scripts automatically. Ensure the script is registered in any layout.
```astro
---
import { pwaInfo } from 'virtual:pwa-info';
export interface Props {
title: string;
}
const { title } = Astro.props as Props;
---
{title}
{ pwaInfo && }
```
--------------------------------
### Prompt for Update and Offline Ready Notification
Source: https://vite-pwa-org.netlify.app/frameworks/nuxt
Shows how to use the `$pwa` injection to display notifications for offline readiness and prompt users to update the PWA when a new version is available.
```APIDOC
## Prompt for Update and Offline Ready
### Description
This example demonstrates how to access the PWA state within your Vue components using `useNuxtApp().$pwa`. It shows how to display a message when the app is ready for offline use and how to prompt the user to reload the page when a new version is available.
### Usage in `
New content available, click on reload button to update.
```
```
--------------------------------
### Use Manifest Icon via src Attribute
Source: https://vite-pwa-org.netlify.app/guide/static-assets
Shows how to use a PWA manifest icon referenced from `src/assets` by setting the `src` attribute of an image element.
```javascript
// src/main.js or src/main.ts
// can be any js/ts/jsx/tsx module or single file component
document.getElementById('#app').innerHTML = `
`
```
--------------------------------
### Laravel Serve Command with Custom Port
Source: https://vite-pwa-org.netlify.app/frameworks/laravel
Command to run the Laravel development server on a specific port, recommended to avoid conflicts with other PWA projects.
```bash
php artisan serve --port=8082
```
--------------------------------
### Configure Assets Generation in package.json
Source: https://vite-pwa-org.netlify.app/assets-generator/cli
Define a script in your package.json to run the PWA assets generator with specific options.
```json
{
"scripts": {
"generate-pwa-assets": "pwa-assets-generator --preset minimal-2023 public/logo.svg"
}
}
```
--------------------------------
### Configure Global Security Headers
Source: https://vite-pwa-org.netlify.app/deployment/vercel
Applies security-focused headers to all routes to mitigate common web vulnerabilities.
```json
{
"source": "/(.*)",
"headers": [
{
"key": "X-Content-Type-Options",
"value": "nosniff"
},
{
"key": "X-Frame-Options",
"value": "DENY"
},
{
"key": "X-XSS-Protection",
"value": "1; mode=block"
}
]
}
```