0

I am building a Chrome extension using Manifest Version 3, which uses Service Workers as the replacement for background pages. I spent a few days earlier this month trying to understand why import wasn't working, till it turns out that service workers don't support import yet. Obviously I can't add a <script> tag either - service workers don't have a DOM to insert a tag into.

What's the best way to load third party code (like an NPM module or a .js file) inside a service worker?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • If you use webpack it'll handle everything for you and import statement will just work. – wOxxOm Dec 05 '22 at 15:11
  • @wOxxOm yep it does. You can mark as a dupe if you like. The confusion was because `import()` (a function I haven't heard of before) and ES6 `imports` are different things. – mikemaccana Dec 05 '22 at 16:44
  • @wOxxOm it's cool I've done it, thanks for spotting it - I've edited the title on the other post so it reflects the contents better too. – mikemaccana Dec 05 '22 at 16:58
  • hello @mikemaccana, did you able to import the npm package from the service worker? I am facing this issue right now. – Nithur Feb 18 '23 at 14:07
  • @Nithur yes. See the other answer. I use `rollup` to make bundle of the service worker, and the bundle includes all the imports. – mikemaccana Feb 20 '23 at 10:20

1 Answers1

1

Extension service workers aren't exactly the same as web service workers. You can do this, but you need to add the "type" key to your manifest.js.

"background": {
  "service_worker": "background.js",
  "type": "module"
}

There's more information in the extensions documentation.

StormyKnight
  • 509
  • 3
  • 13