ESM module import support in Content Scripts?

3,215 views
Skip to first unread message

Simeon Velichkov

unread,
Mar 6, 2023, 10:13:09 AM3/6/23
to Chromium Extensions
Hey,

I'm leveraging the `chrome.scripting.executeScript` API to inject my code dynamically into pages that potentially may be served with strict CSP rules. And while that works great, with the recent push to ESM only builds some prominent libraries are shipping ESM-only builds now.

Meaning, you have to inject a script that's an ESM module, but there is no way to to specify that's a module and subsequently you get the following error message:

Uncaught SyntaxError: Cannot use import statement outside a module

So I guess my question is, is that even on the roadmap for the `scripting` API or maybe I am missing some other new API that might help with this?

Thanks

wOxxOm

unread,
Mar 6, 2023, 12:42:18 PM3/6/23
to Chromium Extensions, Simeon Velichkov
You can use dynamic import() instead: https://stackoverflow.com/a/53033388. Note that currently it makes your extension detectable via a network request to the importable URL chrome-extension://id/script.js but it'll be fixed when use_dynamic_url is implemented properly.

Simeon Velichkov

unread,
Mar 6, 2023, 1:10:57 PM3/6/23
to Chromium Extensions, wOxxOm, Simeon Velichkov
That's a really nice workaround, also thanks for the tip about the web accessible resources fix coming up.

I really didn't think about the dynamic import being available in case the static one isn't there. However,  in my case in particular I was thinking of having the Mermaid v10 loaded like that, since it is now an ESM only build consisting of large amount of chunks https://cdnjs.com/libraries/mermaid loaded through this thing https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.0.2/mermaid.esm.min.mjs

As you can see this is going to require a lot of imports, all of which are static. I think a proper non-esm build will be needed in order to make this work, since trying to fix this one with a regular expression or something like that seems too error prone and then what if they have circular dependencies with all those dynamic imports .. I have had bad experience in those case with Node.js v18 for example.

wOxxOm

unread,
Mar 6, 2023, 2:26:17 PM3/6/23
to Chromium Extensions, Simeon Velichkov, wOxxOm
Importing static modules inside a dynamically imported module should work the same as inside a statically imported one, however if there's a lot of small files then I would indeed make a single bundle to avoid the internal overhead and such separation doesn't benefit locally loaded files anyway.
Reply all
Reply to author
Forward
0 new messages