jscheiny / safe-units

Type-safe TypeScript units of measure 👷📏
https://jscheiny.github.io/safe-units
MIT License
260 stars 14 forks source link

Distributed package isn't tree-shakable #199

Open aethr opened 1 month ago

aethr commented 1 month ago

I've spent some time today evaluating different unit conversion libraries and I like the concept and API you've created for safe-units, nice job!

I did a test installing your package in my project, and doing one single conversion:

const tonnes = Measure.of(1000, kilograms, 't');
function kgToMt(kg: number) {
  return Measure.of(kg, kilograms).valueIn(mega(tonnes));
}

Then I did some bundle analysis on my project, and saw that the entire safe-units package was included in one of my bundles, adding about 25kb (uncompressed). Very close to the numbers reported in https://bundlephobia.com/package/safe-units@2.0.1.

One of the things I liked about your module design was that you should be able to import only what you need, which is a problem with many of the conversion libraries (just because I need to convert kg to Mt doesn't mean I need to convert baskets of fish to football fields at the speed of marmalade!).

So I checked out a local fork of safe-units and made some small changes and was able to get the bundle size in my project down to 12kb. Mainly this included:

Would you be open to PRs that are focused on making the package tree shakeable and trimming down the exported bundle size? I would be happy to contribute and it would make your library much more desirable for use in my projects.

jscheiny commented 1 month ago

Hey, thanks for your interest and investigating this. I would absolutely be open to a PR to make this package tree shakeable!

aethr commented 1 month ago

Great, I'll see if I can put something together this week.

Is it important for you that this module ships an es6 module and a commonjs build? Going all in on es6 modules would be simpler on the infrastructure side, and I suspect most people are starting new projects with es6 modules.

Very non-scientific data from reddit (lol): https://www.reddit.com/r/node/comments/1cfut05/circa_2024_do_you_start_a_new_javascript_projects/

Just switching tsconfig to es6 module/target would get the benefit of the changes I made in my experiement. To support a CJS and ESM build, we'll need two build commands and two tsconfigs, but plenty of libraries do it so it shouldn't be too hard to set up.

jscheiny commented 1 month ago

I think that switching fully over to ES6 would be a breaking change at this time, and I just made one, so I'm somewhat hesitant to do that again so soon. If you think it would not be too much extra work to do both, that would be my preference.

aethr commented 1 month ago

Makes sense! I'll do some reading and see what a good approach is and cook something up.