Olr
(Olr)
July 25, 2017, 5:41pm
1
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?
jorgev
July 27, 2017, 12:02am
2
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.
Olr
(Olr)
July 27, 2017, 5:15am
3
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?
bluelemon
(Amalfi)
September 30, 2017, 4:58pm
4
I’m having the same problem!
NilkasG
(Niklas Gollenstede)
October 2, 2017, 2:20pm
5
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.
Tim_Babych
(Tim Babych)
October 22, 2017, 11:05am
7
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>
jongund
(Jon Gunderson)
October 22, 2019, 4:04pm
9
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?
chikl
July 24, 2023, 6:31pm
10
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 .)