'Chrome Extension Manifest v3 - Background script (aka service worker) cannot use npm modules?

I noticed again a very interesting phenomenon regarding Chrome Extension development. I work with npm and webpack. I installed a npm module called 'tldts' to make URL processing easier. The module works great in all areas of my extension (popup, options, content-script, own page, ...) ... but as soon as I use it in my background script (aka service worker) nothing works more. Nothing! And the best part ... I do not get any errors. I checked all consoles. Maybe someone has any ideas what could cause this problem. So actually I cannot show you any errors because there are no errors >.<?



Solution 1:[1]

In order to use import statements in your background script you need to set the mode to "module" in your manifest.json:

{
  "background": {
    "service_worker": "path/to/background.js",
    "mode": "module"
  }
}

That will allow you to do:

// background.js
import foo from 'bar'

// code...

Otherwise you'll need to use the importScripts() function:

// background.js
importScripts('./path/to/bar.js')

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 Evan Butler