[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>