DEV Community

Discussion on: Custom Service Worker Logic in Typescript on Vite

Collapse
 
abarke profile image
Alex Barker • Edited

I think it's important to note that this only works when running vite build and does not work with the dev server when running vite.

I settled for a different approach which doesn't require vite-plugin-pwa and uses tsc --watch to run in parallel with vite.

I put the sw.ts file in the sw dir to keep config separated between tsconfig.sw.json and tsconfig.json files.

This works a treat and will watch and emit the sw/sw.ts to public\sw.js for Vite dev server to use as a static asset.

Just run yarn dev

package.json

{
  "name": "vite",
  "version": "0.0.0",
  "scripts": {
    "dev": "run-p --print-label dev:*",
    "dev:vite": "vite",
    "dev:swrk": "tsc --watch --project tsconfig.sw.json",
    "build": "tsc && vite build && tsc --project tsconfig.sw.json",
    "serve": "vite preview"
  },
  "devDependencies": {
    "npm-run-all": "^4.1.5",
  }
}
Enter fullscreen mode Exit fullscreen mode

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM", "WebWorker"],
    "moduleResolution": "Node",
    "strict": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
  },
  "include": ["src"],
}
Enter fullscreen mode Exit fullscreen mode

tsconfig.sw.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "lib": ["ESNext", "WebWorker"],
    "noEmit": false,
    "strict": false,
    "outDir": "public",
    "target": "ESNext",
  },
  "include": [
    "sw"
  ],
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
_hariti profile image
abdellah ht • Edited

You saved me a lot of time ❤️

Collapse
 
antonofthewoods profile image
Anton Melser

This obviously won't trigger any sort of reload for the SW when the SW code changes, right?

Collapse
 
mikemaccana profile image

It's worth also adding "isolatedModules": false - otherwise you'll get warnings in VScode asking you to add export to your scripts, and then Chrome/Edge etc will complain with "Unexpected token 'export'".

// See comment at https://dev.to/wtho/custom-service-worker-logic-in-typescript-on-vite-4f27#comment-1n0i7

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "lib": ["ESNext", "WebWorker"],
    "noEmit": false,
    "strict": false,
    "outDir": "public",
    "target": "ESNext",
    // Makes script require 'export' and Chrome will fail to load extensions with
    // "Unexpected token 'export'"
    "isolatedModules": false
  },
  "include": ["service-worker/service-worker.ts"]
}
Enter fullscreen mode Exit fullscreen mode