6

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?

Ginpei
  • 2,958
  • 5
  • 15
  • 25
  • 2
    AFAIK modules aren't supported in content scripts. Probably because those are not like the extension pages with their own URL, but just a bunch of scripts "sideloaded" along web pages. – wOxxOm May 14 '18 at 06:06

1 Answers1

3

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:

  1. bundlers comparison: https://medium.com/@ajmeyghani/javascript-bundlers-a-comparison-e63f01f2a364

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

icl7126
  • 5,740
  • 4
  • 53
  • 51