[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'] }) } }