Swoff Swoff

React + Vite

Set up Swoff with React + Vite.

React + Vite

Concise adapter for React + Vite projects.

Create Project

npm create vite@latest my-app -- --template react-ts
cd my-app && npm install

Project Structure

my-app
├── src
│   └── main.tsx
├── swoff
│   ├── sw-template.js
│   ├── sw-generator.js
│   ├── sw-injector.js
│   └── swoff.d.ts
└── package.json

Entry Point (src/main.tsx)

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { initServiceWorker } from '../swoff/sw-injector'

initServiceWorker()

ReactDOM.createRoot(document.getElementById('root')!).render(<App />)

Add Patterns

Copy from Patterns:

  1. SW Templateswoff/sw-template.js
  2. Build Scriptswoff/sw-generator.js (output dir: dist/)
  3. Client Registrationswoff/sw-injector.js
  4. TypeScript Declarationsswoff/swoff.d.ts

Update package.json:

{
  "scripts": {
    "build": "vite build && node swoff/sw-generator.js"
  }
}

Output Directory

Vite outputs to dist/ by default. Your swoff/sw-generator.js should write sw-v*.js and version.json to dist/.

Build & Test

npm version patch
npm run build

Test offline: DevTools → Application → Service Workers → Check "Offline".

Next Steps

On this page