nismod / irv-frontend

IRV frontend
MIT License
2 stars 0 forks source link

Clean up D3 submodule imports #66

Open mz8i opened 2 weeks ago

mz8i commented 2 weeks ago

I noticed one of the last commits by @tomalrussell was cleaning up the d3 imports a bit. This has been annoying how d3 needs to be imported in projects relying in ES6 modules in quite a different manner than it used to work back in the days of global objects. Especially when you need to use functions from more than two submodules in one file. Recently I came up with this approach on a different project:

[in a file such as /lib/d3.ts]:

import * as d3Array from 'd3-array';
import * as d3Format from 'd3-format';
import * as d3Interpolate from 'd3-interpolate';
import * as d3Scale from 'd3-scale';
import * as d3ScaleChromatic from 'd3-scale-chromatic';

export const d3 = {
  ...d3Scale,
  ...d3ScaleChromatic,
  ...d3Array,
  ...d3Interpolate,
  ...d3Format,
};

// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace D3 {
  export import scale = d3Scale;
  export import scaleChromatic = d3ScaleChromatic;
  export import array = d3Array;
  export import interpolate = d3Interpolate;
  export import format = d3Format;
}

The d3 object contains all the exports from all the installed submodules. They need to be manually destructured just once in this central file. Later, it's enough to just import d3 from this file, and because it's a named export, it works well with IntelliSense etc. Usage is:

import { d3 } from '@/lib/d3';

const scale = d3.scaleLinear(/*...*/);

The D3 namespace helps with the fact that it's not possible to destructure and re-export types. Usage is:

import { type D3 } from '@/lib/d3';

let scale: D3.scale.ScaleLinear<number, number> = undefined;

/* ... */

I won't change this for now, but something to consider. I've been quite happy with the DX this provides on other projects.

tomalrussell commented 2 weeks ago

This was the commit in question: 3bc0da730f6d0bfa351934300e1eff85798c1c22

The proposal sounds reasonable to me, the hoops to jump through type checking and submodule imports are not awesome right now.

cc @shiarella for any comments?