Using modules client-side with import maps

Hi folks,

I have been through a number of approaches now to trying to use npm modules in client-side code. In particular I’d like to use d3. I know it is possible to simply use a script tag to bring in d3 before my own client-side code, but I would prefer the cleanliness of modules and namespaces.

As far as I can tell there are three possible approaches to this problem, which I have tried all of with mixed success:

1. Write using npm-style require() etc and then build the whole package with some bundler, and reference the bundled script in the html

I’ve had some success with this approach in the past, but I don’t like the clunkiness and constant rebuilds, especially when I can’t automate them. Different bundlers have varying levels of accessibility for a relatively novice javascript coder.

2. Write using npm-style require(), and use browserify in the server code to return browser-compatible versions of your scripts

This seems promising but what appears to be the canonical example of this on glitch no longer works and it’s unclear why. I haven’t been able to get this approach working

3. Make use of ES6 modules (and ideally import maps, plus ES6 modules shims for browsers that don’t support import maps yet)

This is my preferred solution, but I haven’t been able to get it working yet either. I have made a minimal implementation using an import map which does appear to successfully import d3 (the d3 code appears in sources in developer tools) but I haven’t been able to actually use the module within the script that imports it – trying to reference any d3 functions just throws errors or returns undefined, as you can see in the example.

(I’m also unsure if I should preferentially be referring to local (to my glitch server) versions of the modules I want to import or using CDNs like Unpkg or whatever.)

I’d be very grateful if anyone could shed any light on what I’m doing wrong here, or alternatively offer a better approach to client-side modules. Cheers.