Since the latest Firefox supports ES Modules without flags as well as Chrome, I would like to use import
/export
for my web extension (add-on). Pop up, background and option pages were OK by simply using <script type="module">
.
How do you make modules work in content script?
I tried and saw followings:
(1) Just write import
in a acript declared at content_scripts.js
in manifest.json
import Foo from './foo.js';
(Chrome) Uncaught SyntaxError: Unexpected identifier
Firefox doesn't work with no errors.
(2) Run through tabs.executeScript()
browser.tabs.executeScript(undefined, {
file: "foo.js",
});
(Chrome) Uncaught SyntaxError: Unexpected identifier
(Firefox) Error: import declarations may only appear at top level of a module
(3) Insert a script element created with type="module"
const el = document.createElement("script");
el.src = browser.extension.getURL("foo.js");
el.type = "module";
document.body.appendChild(el);
(Chrome) Uncaught (in promise) ReferenceError: browser is not defined
(Firefox) ReferenceError: browser is not defined
Do you have any other idea?
One easy solution is using some bundler to bundle your content script.
It may sound complicated, but with bundler like Rollup you can do this very easily with super simple "rollup.config.js" file:
export default {
input: 'content_script.js',
output: {
file: 'bundle_content_script.js',
format: 'iife',
},
};
Rollup will only replace your imports with actual code, so there is no boilerplate and the code is still readable.
You may also want to read:
bundlers comparison: https://medium.com/@ajmeyghani/javascript-bundlers-a-comparison-e63f01f2a364
bundling multiple scripts: https://github.com/rollup/rollup/issues/703
Using bundler will also speed-up loading time, for me it went down from 335ms to 63ms (but I have 100+ modules now).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With