2

This is my problem: I created a library to use within Chrome extensions. This library exports two classes, one of which should be imported in the background script and one in the content scripts.

The background script (and other scripts that are used in the extension pages) can handle modules, so I would like to use the native "import"/"export" feature of ES6 Modules.

The content scripts do not support modules. That means that if I use the "export" keyword in my library script, that will throw an error, and I won't be able to use the library anymore.

Currently, I'm not implementing modules at all, and that solves the problem, but I would like to implement this functionality, so that it can be used when someone has access to it.

Is there a way to offer my library functionality as both a module and a non-module for both kind of scripts? Is that actually something that I should do?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Drago96
  • 1,265
  • 10
  • 19
  • There's no way other than those listed in [How to import ES6 modules in content script for Chrome Extension](https://stackoverflow.com/q/48104433), and of course building the extension using webpack or a similar tool. – wOxxOm Sep 09 '20 at 10:45
  • Thank you for your comment. I did saw that thread, and dynamic imports are really cool, but the methods explained there can't be applied to a broad range of users (remember that this is a library). Dynamic imports (which are the only usable method in my situation) may be a little too restrictive when it comes to chrome versions... what do you think? – Drago96 Sep 09 '20 at 10:53
  • "*Is there a way to offer my library functionality as both a module and a non-module*" - yes, of course there is. But not as a single file. You will need to distribute an ES6 build and a script build. – Bergi Sep 09 '20 at 11:13
  • Thanks @Bergi , it look like a good compromise (though i will have to come up with a good way to set up the development environment for that). If there will be no better answers, i'll probably do it that way – Drago96 Sep 09 '20 at 13:14

1 Answers1

1

In the end, I set up two git branches:

1 - In the first one, I just kept the file without the "export", so no ES6 modules capabilities

2 - This other branch, I decided to set it up to be published on NPM, and in this one I exported my classes. If you use NPM for your development, it's already very probable that you also have a bundler like webpack to keep track of modules and dependencies.

Whenever I do a change, I do it in the master (no exports) branch, and then I merge the changes in the npm branch, to avoid writing the same code twice

Drago96
  • 1,265
  • 10
  • 19