79
loading...
This website collects cookies to deliver better user experience
// vite.config.ts
import { defineConfig } from 'vite'
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.svg'],
}),
],
})
vite build
and vite preview
.fetch
requests the website runs to obtain rendered data, which is also a feature the service worker provides, or you might want to handle push
notifications on your own.src/sw-custom.ts
. I setup the typings by following some advice on this GitHub issue and ended up using this:/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />
const sw = self as unknown as ServiceWorkerGlobalScope & typeof globalThis;
sw.addEventListener('install', (event) => {
// ...
})
sw
instead of self
. Depending on the Typescript version, you might have to adjust the typings. Make sure you check out the aforementioned GitHub issue.html
entry file(s), OR a library with a javascript entry file (library mode). In our case, we need both: The base website with index.html
and the Service Worker as bundled Javascript.import { rollup, InputOptions, OutputOptions } from 'rollup'
import rollupPluginTypescript from 'rollup-plugin-typescript'
import { nodeResolve } from '@rollup/plugin-node-resolve'
const inputOptions: InputOptions = {
input: 'src/sw-custom.ts',
plugins: [rollupPluginTypescript(), nodeResolve()],
}
const outputOptions: OutputOptions = {
file: 'dist/sw-custom.js',
format: 'es',
}
const bundle = await rollup(inputOptions)
await bundle.write(outputOptions)
await bundle.close()
plugin-node-resolve
here to include any imported library from other modules in the bundle of the service worker. If your custom Service Worker has no imports, you do not need this plugin./sw-custom.js
from the app.const CompileTsServiceWorker = () => ({
name: 'compile-typescript-service-worker',
async writeBundle(_options, _outputBundle) {
const inputOptions: InputOptions = {
input: 'src/sw-custom.ts',
plugins: [rollupPluginTypescript(), nodeResolve()],
}
const outputOptions: OutputOptions = {
file: 'dist/sw-custom.js',
format: 'es',
}
const bundle = await rollup(inputOptions)
await bundle.write(outputOptions)
await bundle.close()
}
})
export default defineConfig({
plugins: [
VitePWA(),
CompileTsServiceWorker().
],
})
vite-plugin-pwa
exposes the option in the plugin through the workbox.importScripts
option:export default defineConfig({
plugins: [
VitePWA({
registerType: 'autoUpdate',
workbox: {
importScripts: ['./sw-functional.js'],
globIgnores: ['**/node_modules/**/*', '**/sw-custom.js'],
},
}),
CompileTypescriptServiceWorker().
],
})
sw-custom.ts
, I run nodemon to get an automatic reload:npx nodemon --exec 'npx vite build && npx vite preview' -w src -w vite.config.ts -e 'ts,js'