Search code examples
serviceworkersapper

Sapper and Service Workers


This is more of a service worker question, although it could be more specific to Sapper. I really don't know, as I am the first to admin I struggle with Service Workers, have barely used them, and feel like they are a pain the butt very often.

Basically, no matter what I do, I cannot get localhost:3000 to stop loading the old copy of the app. I've unregistered the service worker in various ways, including try to programmatically unregister. I've clear caches, and even cleared all browsing data from the browser. The server from my Sapper dev environment is NOT running.

This is happening with Brave, but behaves the same in Opera, and seems like a general Chromium scenario. I don't user Firefox or Safari, but may test in one soon to see what behavior happens there.

Here is a clip showing how I try to unregister the Service Worker.

https://youtu.be/Cb24I_fEklE


Solution

  • I used this little trick that works like a charm. In your rollup.config.js, there's a serviceWorker object in the outputs object.

    serviceworker: {
        input: config.serviceworker.input(),
        output: config.serviceworker.output(),
        plugins: [
          resolve(),
          replace({
            "process.browser": true,
            "process.env.NODE_ENV": JSON.stringify(mode),
          }),
          commonjs(),
          !dev && terser(),
        ],
    
        preserveEntrySignatures: false,
        onwarn,
      },
    

    Define a variable dev on top if not already declared:

    const dev = process.env.NODE_ENV === "development";
    

    Now change your service worker config like this:

    serviceworker: !dev && {
        input: config.serviceworker.input(),
        output: config.serviceworker.output(),
        plugins: [
          resolve(),
          replace({
            "process.browser": true,
            "process.env.NODE_ENV": JSON.stringify(mode),
          }),
          commonjs(),
          !dev && terser(),
        ],
    
        preserveEntrySignatures: false,
        onwarn,
      },