Search code examples
babeljsservice-workerprogressive-web-appsparceljs

How do I use service workers in parcel?


I have a service worker that comes from my js/index.js:

import '../scss/app.scss';
// Detect if service workers enabled
if ('serviceWorker' in navigator) {
  try {
    navigator.serviceWorker.register('../sw.js');
    console.log('Service Worker Registered');
  } catch (error) {
    console.log('Service Worker Register Failed');
  }
}

and my sw.js in my root directory:

const staticAssets = ['./', 'scss/app.scss', 'js/index.js'];
self.addEventListener('install', async (event) => {
  const cache = await caches.open('min-static');
  cache.addAll(staticAssets);
});
self.addEventListener('fetch', (event) => {
  console.log('fetch');
});

Is babelized and put into the dist folder by parcel. When it's built and I go to localhost, I open chrome tools and go into the application tab. I go into the cache storage tab and: Cache Storage just has a heading that says cache storage. There's also a console error that says ReferenceError: regeneratorRuntime is not defined What's going on? Why doesn't my website get nicely cached like in The PWA Tutorial? Shouldn't it look like this: A nice table of the cached files that I DON'T HAVE? Granted, I am running everything through babel, but why isn't it working?

Thanks in advance!


Solution

  • The error regeneratorRuntime is not defined happens because Babel (used by Parcel to transpile code) is generating a polyfill for ES6 generators in your build. To disable that (and fix your issue) you need to specify you don't want the generators to be transpiled.

    Easy fix

    An easy way to fix that would be to add the following lines to your package.json:

    "browserslist": [
      "since 2017-06"
    ],
    

    This makes it so that your build will only attempt to support browser versions released since 2017-06, which do support ES6 generators and therefore do not need polyfills for that feature.

    Alternatives

    You might want to experiment with these values depending on your application's target audience, for example this should also work:

    "browserslist": [
      "last 3 and_chr versions",
      "last 3 chrome versions",
      "last 3 opera versions",
      "last 3 ios_saf versions",
      "last 3 safari versions"
    ]
    

    More information

    If you want to check which features are supported by each browser you can check here.

    And if you want to check which options are valid for browserslint check here.

    There is also more discussion available regarding your specific issue here.