d3.jsnvd3.jssystemjsjspmdynamic-script-loading

Configure SystemJS to always return same instance of library


I have two jspm modules, ModuleA and ModuleB. Both depend on the d3.js library. I have a third jspm module, ModuleC, which depends on ModuleA and ModuleB. When I run ModuleC, I get d3 errors, even though ModuleA and ModuleB both work in isolation.

This is happening because ModuleA relies on a d3 plugin (nvd3) which adds functionality to the d3 instance it is provided by SystemJS. However, when ModuleB loads, it replaces this version of d3 with its own, fresh version of d3, effectively erasing the plugin that ModuleA relies on.

How can I configure SystemJS to provide the same instance of d3 to both ModuleA and ModuleB?


Solution

  • Figured it out. SystemJS does provide the same instance of modules by default. However, the modules being requested must be the same version and from the same source.

    In my case, ModuleA was depending on d3 directly, via jspm install d3, which pulled its version of d3 from GitHub. ModuleB was depending on d3 indirectly through a dependency of angular-nvd3, which eventually resolved to the npm version of d3. Because SystemJS had no way of knowing these were the same library, it loaded both versions.

    Once I updated ModuleA to use the npm version of d3 (jspm install npm:d3@3.5.17), both modules played nicely in ModuleC and d3 was only loaded once.