Search code examples
javascriptgoogle-chrome-extensionfirefox-addonchrome-extension-manifest-v3

How can I use import in background.js in my firefox and chrome extensions?


I'm using vanilla javascript and am doing this at the top of background.js for firefox:

  "background": {
    "scripts": ["scripts/background.js"]
  },

and chrome:

  "background": {
    "service_worker": "scripts/service-worker.js"
  },

In both service-worker.js and background.js I need to use import { thing } from './scripts/utils.js'

How can I do this? I get an error in firefox that says import can only be used at the top of a module.


Solution

    • In ManifestV2 Firefox/Chrome specify page + load the script file explicitly as a module:

      manifest.json:

        "background": {
          "page": "bg.html"
        },
      

      bg.html:

      <script src="scripts/background.js" type="module"></script>
      
    • In ManifestV3 Chrome specify type:

      manifest.json:

        "background": {
          "service_worker": "scripts/service-worker.js",
          "type": "module"
        },