0

I'm trying to build a module which uses d3, but I don't want to bundle d3 with that module and, crucially, I don't want to have to bind d3 to the window. The module is to be installed on another project with npm as a git dependency. On the module I have a set up something like this:

output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].min.js',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
  externals: [
    {
      "d3": {
        root: "d3"
      }
    }
  ]

and in the project it's installed onto I want something like this:

import d3 from 'd3'
import example from 'example'

However, that only works if I also do this:

import d3 from 'd3'
window.d3=d3
import example from 'example'

Is it possible to use both modules without touching the global scope?

Hello World
  • 1,102
  • 2
  • 15
  • 33

2 Answers2

0

try change

  externals: [
    {
      "d3": {
        root: "d3"
      }
    }
  ]

to

  externals: [
    {
      "d3": {
        commonjs: "d3"
      }
    }
  ]

Descried in the doc. by setting to root, The library should be available as a global variable

loveky
  • 1,002
  • 1
  • 11
  • 18
0

Because the two modules exist separately, they each have their own closure. The only place to share a 3rd dependency is a scope external to both, traditionally global scope. You can practice dependency injection.

So, instead of

module.exports = function do_a_thing() {
  // use d3 here
}

You do

module.exports = function do_a_thing_generator(d3) {
  return function do_a_thing() {
    // use d3 here
  }
}

Then, eventually

import d3 from 'd3'
import exampleInit from 'example'

const example = exampleInit(d3)
Omri
  • 278
  • 2
  • 9