Simple way to register service worker in a Vite project
npm i @gautemo/vite-plugin-service-worker -D
JavaScript
Add serviceWorkerPlugin
to your vite.config.js
and specify your service worker filename:
import { defineConfig } from 'vite'
import { serviceWorkerPlugin } from '@gautemo/vite-plugin-service-worker'
export default defineConfig({
plugins: [
serviceWorkerPlugin({
filename: 'sw.js',
}),
],
})
Then register your service worker in your src code.
navigator.serviceWorker.register('/sw.js', {
type: 'module',
})
TypeScript
Add serviceWorkerPlugin
to your vite.config.ts
and specify your service worker filename:
import { defineConfig } from 'vite'
import { serviceWorkerPlugin } from '@gautemo/vite-plugin-service-worker'
export default defineConfig({
plugins: [
serviceWorkerPlugin({
filename: 'sw.ts',
}),
],
})
Then register your service worker in your src code. Import the serviceWorkerFile
so the plugin can alternate between the .js and .ts extension based on if it's in dev or build.
import { serviceWorkerFile } from 'virtual:vite-plugin-service-worker'
navigator.serviceWorker.register(serviceWorkerFile, {
type: 'module',
})
Also add the type to your vite-env.d.ts
file:
declare module 'virtual:vite-plugin-service-worker' {
export const serviceWorkerFile: string
}
Project with TypeScript: module-ts
pnpm build
npm publish --access=public