Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up D3 submodule imports #66

Open
mz8i opened this issue Nov 8, 2024 · 1 comment
Open

Clean up D3 submodule imports #66

mz8i opened this issue Nov 8, 2024 · 1 comment

Comments

@mz8i
Copy link
Contributor

mz8i commented Nov 8, 2024

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
Copy link
Member

This was the commit in question: 3bc0da7

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants