jaredpalmer / tsdx

Zero-config CLI for TypeScript package development
https://tsdx.io
MIT License
11.28k stars 507 forks source link

Recommendations on exporting multiple functions in a utility library #713

Closed Svish closed 4 years ago

Svish commented 4 years ago

Not sure if this is a general javascript/typescript question or a tsdx question, but I needed to create a @my-org/common utility package (custom formatting, validation, some special array functions, etc., etc.), and, well, I've hit at least more than 1 of the "things to screw up" with no idea of how to do it right.

So, tsdx looks promising, but I have a question about how one would write/structure a general utility library. What does one do about the main index.ts file? Especially in relation to tree-shaking and other related things.

Do I need to export every single utility function from index.js? And if not, how would one import one of these functions?

I've tried to look for examples, but most seem to be single function or simple react component type packages, where of course the main index.ts makes perfect sense. 🤔

agilgur5 commented 4 years ago

It is indeed more of a general JS question.

Yes, exporting every utility function from index.ts is one way of doing it. Bundlers should normally tree-shake out any unused imports, but this apparently does not always seem to be true unless you also set preserveModules: true for Rollup (see that linked issue for details on that).

Multi-entry is the other option, that is, having different files containing different imports, i.e. @my-org/common/validation, @my-org/common/array-func-a, etc. Support is still pending for this in TSDX (#367 ) because it is a bit breaking and it is very manual currently.