[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

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

<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).


export const a = {}

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.)