Skip to content

Latest commit

 

History

History

custom-ts-worker

next-pwa - custom worker example

[TOC]

This example demonstrates how to use next-pwa plugin to turn a next.js based web application into a progressive web application easily. It demonstrates how to add custom worker code to the service worker generated by workbox.

New Method

Simply create a worker/index.ts and start implementing your service worker. next-pwa will detect this file automatically, and bundle the file into dest as worker-*.js using webpack. It's also automatically injected into sw.js generated.

In this way, you get benefit of code splitting and size minimization automatically. Yes! require modules works! Yes! you can share codes between web app and the service worker!

  • In dev mode, worker/index.ts is not watched, so it will not hot reload.

Custom Worker Directory

You can customize the directory of your custom worker file by setting the customWorkerDir relative to the basedir in the pwa section of your next.config.js:

const withPWA = require('next-pwa')({
  customWorkerDir: 'serviceworker'
  // ...
})

module.exports = withPWA({
  // next.js config
})

In this example, next-pwa would look for serviceworker/index.ts.

Old Method (Still Works)

Basically you need to create a file such as worker.js in public folder, then add an option importScripts to pwa object in next.config.js:

const withPWA = require('next-pwa')({
  dest: 'public',
  importScripts: ['/worker.js']
})

module.exports = withPWA({
  // next.js config
})

Then service worker generated will automatically import your code and run it before other workbox code.

Usage

Open in Gitpod

cd examples/custom-ts-server
yarn install
yarn build
yarn start

Recommend .gitignore

**/public/workbox-*.js
**/public/sw.js
**/public/worker-*.js