alexbol99 / flatten-interval-tree

Interval binary search tree
MIT License
41 stars 21 forks source link

build: fix ESM exports #49

Closed noomorph closed 8 months ago

noomorph commented 9 months ago

This pull request fixes a blocker issue when trying to use this module as a "module" (ESM).

Tested on Node.js 14, 16, 18, 20 with require('@flatten-js/interval-tree') and import.

You can verify the fix via my temporary fork: @noomorph/interval-tree.

Problem

Expected:

import IntervalTree from '@flatten-js/interval-tree';

typeof IntervalTree // function

Actual:

import IntervalTree from '@flatten-js/interval-tree';

typeof IntervalTree // object šŸ’„ 

Reason

In fact, this line in your package.json doesn't work:

  "module": "dist/main.esm.js",

You can easily check that by deleting that file, and import IntervalTree from '@flatten-js/interval-tree'; will still work because it never looked there, to start with ā€“ it always uses the CommonJS version.

So the fix is to add exports section which Node.js really recognizes:

+ "exports": {
+   "types": "./index.d.ts",
+   "require": "./dist/main.cjs",
+   "import": "./dist/main.mjs",
+   "default": "./dist/main.umd.js"
+ },

I had to rename esm.js to .mjs because Node.js doesn't tolerate other extensions, e.g.:

> await import('@flatten-js/interval-tree')
(node:58606) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

Thanks in advance for looking! I hope you and your family are safe.

alexbol99 commented 8 months ago

@noomorph Thank you for your contribution Fixing this issue was very important.

noomorph commented 8 months ago

Sure, happy to help. I already switched to your version in my project.