'Import a dependency to a service worker

Until now I have been using importScripts to import external dependencies into my service worker. But now I see in the documentation of two of my dependencies that to use their latest version I should be using the import statement:

  1. Firebase Cloud Messaging
  2. Google Workbox

Everywhere else I look (here on SO or just by Googling) it says to use importScripts in service worker. So am I missing something?

I am using Webpack as bundler.



Solution 1:[1]

It is possible, in some browsers, to use runtime ES module imports to pull additional code into the ServiceWorkerGlobalScope. The lack of universal browser support means that you might have trouble relying on that exclusively.

Because of this, it's still very common to do one of two things:

  • Use ES module imports as a build-time signal to a bundler, like Rollup/webpack/esbuild, to include code in a final service worker bundle that ends up being run in the browser. This is what the documentation for, e.g., Workbox steers folks towards, and includes examples of. This approach means that the bundler can eliminate code that you don't end up referencing from the Workbox packages you import.

  • Use importScripts(), as before. This is still supported in Workbox, even though it's not the preferred approach.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeff Posnick