Add esm build and package.json exports
Resolves #199.
Description
This change adds a tsconfig.cjs.json and tsconfig.esm.json, both extending a common tsconfig.base.json, which will allow the project to generate two separate builds to distribute. Within package.json the old module property and newer exports property will allow downstream consumers to automatically use the build which is compatible with their tooling. This was mainly prepared following this guide: https://blog.mastykarz.nl/create-npm-package-commonjs-esm-typescript/
The build:cjs and build:esm npm commands are used to generate each build and place a minimal package.json in each folder to avoid needing to use the .mjs extension on the files in the esm build. See https://www.sensedeep.com/blog/posts/2021/how-to-create-single-source-npm-module.html "Per ESM/CJS package.json" for more detail.
Testing
I created two minimal projects to test these changes, a commonjs project and an esm project with a minimal entry file:
import { grams, kilo, Measure } from 'safe-units';
const m = Measure.of(123, grams);
console.log(m.valueIn(kilo(grams)));
Both projects use Rollup to create a bundle, which I measured for size. I built each project twice, once with "safe-units": "^2.0.1" from npm, and once with "safe-units": "../safe-units" to build with my local version of the module.
Results
CommonJS project with safe-units from npm: index.js 48K
CommonJS project with safe-units from this branch: index.js 48K
ESM project with safe-units from npm: index.js 48K
ESM project with safe-units from this branch: index.js 24K
As a side note, even in the ESM project I couldn't build the bundle without the @rollup/plugin-commonjs module, but this was no longer necessary when building from this branch, since a native esm module is now available.
Just a thought here. Maybe bunchee and attw could be handy?
I got these tools from digging in swr.
Bunchee
It helps to minimize configurations, eliminate boilerplate while providing support for old fart clients, typescript clients, weird clients, etc.
Attw – Are the types wrong
It checks whether your distribution covers for all their cases it claims support of.
Here's an example output from running it against @adam-rocska/markdown-table :
Build tools:
- @arethetypeswrong/cli@^0.15.4
- typescript@^5.5.4
No problems found 🌟
┌───────────────────┬───────────────────────────────┐
│ │ "@adam-rocska/markdown-table" │
├───────────────────┼───────────────────────────────┤
│ node10 │ 🟢 │
├───────────────────┼───────────────────────────────┤
│ node16 (from CJS) │ 🟢 (CJS) │
├───────────────────┼───────────────────────────────┤
│ node16 (from ESM) │ 🟢 (ESM) │
├───────────────────┼───────────────────────────────┤
│ bundler │ 🟢 │
└───────────────────┴───────────────────────────────┘