[WebExtension] Import a module in a script

Hello *,

In a background script, I try to import a module with:

import { echo } from "mymodule";

The module <mymodule.js> is in the same location than the background script.

I get the error message:

SyntaxError: import declarations may only appear at top level of a module

Even when the import function is at line 1, I get this error.

Same problem in an action script.

What should I do to import a module?

1 Like

According to the documentation, module support is only on preliminary stages at the moment, so you probably shouldnā€™t be using it for extension code.

1 Like

Sadā€¦
But it seems but we canā€™t use require either like we did in Addon-SDKā€¦

const mymodule = require("./mymodule/submodule.js");
doesnā€™t work either.

Is there no possibility for module at all in WebExtension?

Iā€™m having the same problem!

You can load scripts the same way you do on websites (using <script src="..."> tags).
You can of cause use a module loader (require.js, webpack, ā€¦) that does that for you.

You include your library script in ā€˜scriptsā€™ section of manifest.js:

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

On manifest use:

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

instead of script

on background.html
add

<script type="module" src='./background.js'></script>

There doesnā€™t seem to be any information in the page you linked to about module import support in extensions.

Is there any update on using module import in Firefox extensions?

If anyone is still searching for an answer: You can import a module by using import() (see documentation).

Example:

test.js:
export const a = {}

background.js:
const background = { init() { import('./test.js').then((exports) => { this.b = exports['a'] }) } }

Iā€™m new to all these, and donā€™t know anything about the situation in prior versions of firefox. The discussion above did not resolve my issue.

What worked for me is pretty simple in fact:
Add "type": "module" into the ā€œbackgroundā€ section of manifest.json. Something like this:

{
  ...
  "background": {
    "scripts": ["background.js"],
    "type": "module"
  },
  ...
}

Some other words:
I got the same error message and found this post. To be fair, the error message does not make sense, as I appear to be importing at the top level of a module. I also got a similar error for the export statements at some point while trying different methods to fix this. Luckily, this all got fixed for me at least. (Thanks to the inspiration from this PR.)