d3 / d3-hexbin

Group two-dimensional points into hexagonal bins.
https://observablehq.com/collection/@d3/d3-hexbin
BSD 3-Clause "New" or "Revised" License
240 stars 34 forks source link

Usage in ES6 import #16

Closed DDDgfx closed 5 years ago

DDDgfx commented 5 years ago

How to import this as an ES6 import? Happy to have it renamed (I dont need to have it in d3. namespace , I just want it in my project. Ive tried: import as d3hexbin from "d3-hexbin"; import { hexbin } as d3hexbin from "d3-hexbin"; import d3hexbin from "d3-hexbin/src/hexbin"; import as d3hexbin from "d3-hexbin/src/hexbin"; import * as hexbin from "d3-hexbin";

I got sankey working with this: import * as d3Sankey from "d3-sankey";

But no matter how I import this, im getting an error that it is not a function Hope you can help. - D

mbostock commented 5 years ago

Technically, this repository isn’t setup for consumption as an ES module in environments that support ES modules natively because it uses implicit file extensions in import paths. For example, in index.js, it says:

export {default as hexbin} from "./src/hexbin";

But to be valid ES, it should say:

export {default as hexbin} from "./src/hexbin.js";

This will be fixed in a future version (across all of the D3 modules).

I mention this because the ability to consume this library as an ES module therefore currently requires you to use a nonstandard build tool such as Rollup or webpack. You must configure this tool to observe the module entry point defined in the package.json if you want to be able to import this library using a bare module specifier (and currently that module entry point has an implicit file extension: index instead of index.js). Assuming you have configured your build tool to find the intended entry point, there are two valid styles of imports.

The first is to import the library as a namespace:

import * as d3Hexbin from "d3-hexbin";

const hexbin = d3Hexbin.hexbin();

The second is to import individual symbols:

import {hexbin as Hexbin} from "d3-hexbin";

const hexbin = Hexbin();

Since this library only has one export (hexbin), I’d probably chose the latter, but it’s up to you.

DDDgfx commented 5 years ago

Really appreciate the details here. Im not prepared to roll my own D3, but I can see it might be valuable to do so, but I've wasted enough life energy on webpack and yarn etc.... In the meantime, I just copied hexbin.js elsewhere, changed "default" to

export function hex() {...}

then import { hex } from "../location";

then:

var hexmap = hex()...

This might be bad, but its working. Thanks as always.

NicholasCanova commented 4 years ago

Hey @mbostock was there ever an update on this, or should we continue with the import * as d3Hexbin from 'd3-hexbin'; as the method of importing?

skouzini commented 2 years ago

@mbostock @NicholasCanova I second this. Is the above method mentioned still the way to do it?