d3: D3 packages are incompatible with Node projects that use `"type": "module"`

I hope this is the right place to open this issue, as it’s something that affects all d3-* packages as well as d3 itself. Please redirect me if not!

I’ve created a repo to provide a playground (where you can for example npm link a copy of d3-dsv with the proposed changes to see it working); this issue is a copy of that repo’s README.


As of Node 12 (which is to say all maintained Node versions bar 10, which reaches EOL in April), it’s possible for a Node project to use native JavaScript modules by adding the following to package.json:

{
  "type": "module"
}

Let’s say you’re making such a project, and you want to use (say) d3-dsv, and for extra points you’re using TypeScript, so that your package.json looks like this…

{
  "devDependencies": {
    "@types/d3-dsv": "^2.0.1",
    "@types/node": "^14.14.28",
    "typescript": "^4.1.5"
  },
  "dependencies": {
    "d3-dsv": "^2.0.0"
  },
  "type": "module"
}

…and your tsconfig.json looks like this:

{
  "compilerOptions": {
    "allowJs": true,
    "moduleResolution": "node",
    "noEmit": true
  }
}

In a JavaScript file, which has // @ts-check at the top to enable typechecking, you import d3-dsv but discover that TypeScript yells at you:

Code with TypeScript error message

According to @types/d3-dsv, there’s no default export — you need to use named imports instead. So we switch to using a * import, and now we get nice autocomplete…

TypeScript-powered autocomplete

…and typechecking:

TypeScript-powered typechecking

But when we run the program, it fails:

Error message

That’s because Node believes that d3-dsv is a CommonJS package. When CommonJS is imported from ESM, Node treats module.exports as the default export. In other words, @types/d3-dsv disagrees with d3-dsv itself about what it exports.

It’s not just TypeScript though — d3-dsv disagrees with itself about its exports. That’s because (like all D3 packages) it follows the well-established convention of providing both pkg.main and pkg.module

{
  "main": "dist/d3-dsv.js",
  "module": "src/index.js"
}

…which means that Node can ingest the CommonJS distributable version, while bundlers like Rollup ingest the modern source code. These bundlers, like TypeScript, expect to find named exports:

Rollup error message

In other words, if you’re using native JavaScript modules, you have a choice: you can write D3 programs that run in Node, or you can write D3 programs that typecheck and can be bundled. You can’t do both.

We can fix this!

Luckily this is easily solved, with one small caveat: we add "type": "module" to the package.json files in each package, alongside "exports" (which is how Node resolves e.g. d3-dsv to node_modules/d3-dsv/src/index.js):

  "main": "dist/d3-dsv.js",
  "unpkg": "dist/d3-dsv.min.js",
  "jsdelivr": "dist/d3-dsv.min.js",
  "module": "src/index.js",
+ "type": "module",
+ "exports": {
+   "./package.json": "./package.json",
+   "import": "./src/index.js",
+   "require": "./dist/d3-dsv.js"
+ },
  "bin": {

A new file, dist/package.json, allows the existing dist/*.js files to continue being treated as CommonJS (i.e. this cancels out the "type": "module":

{
  "type": "commonjs"
}

(In future, it might even be possible to get rid of the dist folder once native modules are universally adopted alongside import maps etc, but I’m not suggesting that any time soon given how D3 is used in the wild.)

The caveat is that this is technically a breaking change requiring a semver major release, since someone might currently be using these packages via import and would expect to be able to continue using the default import. We’re talking about fairly extreme early adopters who can probably adapt very easily, and you could argue that the current behaviour is buggy and therefore can be fixed in a patch version. But if it was deemed necessary to support those users, it could be done in a non-breaking way by adding a default export alongside the named exports. For example:

-export {default as dsvFormat} from "./dsv.js";
-export {csvParse, csvParseRows, csvFormat, csvFormatBody, csvFormatRows, csvFormatRow, csvFormatValue} from "./csv.js";
-export {tsvParse, tsvParseRows, tsvFormat, tsvFormatBody, tsvFormatRows, tsvFormatRow, tsvFormatValue} from "./tsv.js";
-export {default as autoType} from "./autoType.js";
+import {default as dsvFormat} from "./dsv.js";
+import {csvParse, csvParseRows, csvFormat, csvFormatBody, csvFormatRows, csvFormatRow, csvFormatValue} from "./csv.js";
+import {tsvParse, tsvParseRows, tsvFormat, tsvFormatBody, tsvFormatRows, tsvFormatRow, tsvFormatValue} from "./tsv.js";
+import {default as autoType} from "./autoType.js";
+
+export {dsvFormat, csvParse, csvParseRows, csvFormat, csvFormatBody, csvFormatRows, csvFormatRow, csvFormatValue, tsvParse, tsvParseRows, tsvFormat, tsvFormatBody, tsvFormatRows, tsvFormatRow, tsvFormatValue, autoType};
+
+export default {dsvFormat, csvParse, csvParseRows, csvFormat, csvFormatBody, csvFormatRows, csvFormatRow, csvFormatValue, tsvParse, tsvParseRows, tsvFormat, tsvFormatBody, tsvFormatRows, tsvFormatRow, tsvFormatValue, autoType};

Thanks for reading this far! Obsessing over details like these is no-one’s idea of a good time. However, now that the shift to a native module ecosystem is well and truly underway, more and more people will start to encounter these issues, and steps like these can minimise the frustration they experience.

D3 has shown impressive leadership in this area in the past and played a crucial role in helping to shift the JS ecosystem towards native modules, so this feels like a natural next step. Onward!

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 75
  • Comments: 28 (10 by maintainers)

Commits related to this issue

Most upvoted comments

I like the idea of going all-in on ESM and doing it as a major version bump.

The main README for d3 still says:

In Node:

const d3 = require(“d3”);

You can also require individual modules and combine them into a d3 object using Object.assign:

const d3 = Object.assign({}, require(“d3-format”), require(“d3-geo”), require(“d3-geo-projection”));

But both usages now seem to be broken.

Keeping the UMD build in dist.

In my libraries, I decided to do what Sindre Sorhus is doing in his projects — slowly migrating them to ESM-only with "type": "module", no conditional exports, and dropping the CommonJS entry point and support for require completely (requiring Node v12+). UMD build is still generated for legacy uses (script tags etc) but it’s not main.

Quick nit.

The currently suggested package.exports won’t work as expected.

You don’t need to you "type": "module" to use ESM in node.js, you can simply use the .mjs file extension. What "type": "module" does is change the interpretation of the .js file extension to be ESM rather than CJS… this means that in a "type": "module" package you can’t use the .js extension for CJS, you can instead use .cjs, which has the excellent slightly unexpected behavior of “just working” in old versions of Node.js as the runtime treats unknown file extensions as CJS (although you need to be explicit about the file extension in your source text, e.g. no automatic file extension resolution with .cjs). If you don’t care about supporting Node.js < 12.20.x you can replicate some of the file extension magic using subpath patterns.

It might be more work than you are looking for but I have an example repo that has everything authored in ESM with the .mjs file extension and uses rollup to transpile a CJS version that is exposed using package.exports. This is a pattern you could explore using to simplify some of this, happy to answer any questions.

https://github.com/mylesborins/node-osc

One thing to keep in mind. If you choose to use package.exports folks will only be able to import files / paths that are defined as subpath exports. Folks mostly get bit by this when they discover they needed to explicitly export their package.json if folks are expecting to be able to import / require it.

Happy to answer any questions

@fregante because given the size of D3’s userbase it’s guaranteed that someone, somewhere, is doing this:

<script src="https://some.npm.cdn/d3"></script>
<script>
  d3.select(...)...
</script>

Removing the UMD dist files would break those apps — acceptable in a major version, but otherwise fraught.

@marvinhagemeister D3 packages don’t expose a bundled ESM version, just the src. So the choice is

  1. rename all the src/**/*.js files to src/**/*.mjs (and live with the subpar authoring experience)
  2. start bundling ESM (and live with the increased complexity, and requirement to use sourcemaps etc)
  3. Use "type": "module" at the top level and "type": "commonjs:" inside dist

For me, 3 is an absolute no-brainer, but it’s also not my decision.

An alternative would be to drop the CJS module. What’s the advantage for a non-node module to keep CJS when it’s just generated from an ESM file and read only by bundlers anyway? To keep esmify-less browserify compatibility? Doesn’t seem worth the effort.

I believe, but could be wrong, that dropping CJS support would potentially make it significantly harder for those using browserify which still has over 1 million downloads a month.

It seems like a UMD module that is included as main should allow browserify to still work, but would be good to confirm that.

On Fri, Feb 19, 2021 at 1:01 PM Curran Kelleher notifications@github.com wrote:

Definitely a concern. It reminds me of the current consistent stream of D3 “bug reports” people submit due to adoption of ES6.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/d3/d3/issues/3469#issuecomment-782239704, or unsubscribe https://github.com/notifications/unsubscribe-auth/AADZYV3TPBSHMJYZP7IBOWLS72RNZANCNFSM4XXJORCA .

// async method
(async function() {
  const d3 = Object.assign({}, await import("d3-format"), await import("d3-geo"), await import("d3-geo-projection"));
  console.log(d3);
})();
// needs "type": "module" in package.json
import * as d3Format from "d3-format";
import * as d3Geo from "d3-geo";
import * as d3GeoProjection from "d3-geo-projection";
const d3 = Object.assign({}, d3Format, d3Geo, d3GeoProjection);
console.log(d3);

Please review https://github.com/d3/d3/pull/3511

If anyone wants to review:

In some cases I couldn’t find how to fix the tests that depend on this being global in the new environment.

Definitely a concern. It reminds me of the current consistent stream of D3 “bug reports” people submit due to adoption of ES6.

@mourner I like the cut of your jib, and if that’s the view of the maintainership then I enthusiastically support it. My only hesitation is that the people who can’t yet adopt ESM in their own projects (for whatever reason) might blame D3 for the incompatibility. If it were to happen in a major version that’s obviously less of a concern.