@gautemo/vite-plugin-service-worker
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

vite-plugin-service-worker

Simple way to register service worker in a Vite project

Install

npm i @gautemo/vite-plugin-service-worker -D

Usage

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
}

Example

Project with TypeScript: module-ts

npm publish

pnpm build
npm publish --access=public

Readme

Keywords

Package Sidebar

Install

npm i @gautemo/vite-plugin-service-worker

Weekly Downloads

42

Version

0.1.0

License

MIT

Unpacked Size

5.79 kB

Total Files

7

Last publish

Collaborators

  • gautemo