Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ES Modules from content_scripts of Web Extension (add-on) [duplicate]

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?

like image 364
Ginpei Avatar asked May 14 '18 03:05

Ginpei


1 Answers

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

like image 197
icl7126 Avatar answered Oct 21 '22 18:10

icl7126