dmonad / lib0

Monorepo of isomorphic utility functions
MIT License
345 stars 62 forks source link

sideEffects and tree-shaking #58

Open holtwick opened 1 year ago

holtwick commented 1 year ago

I ported some parts of lib0 to my open source lib zeed, because I needed some special changes for my usecase. The code is here: https://github.com/holtwick/zeed/tree/master/src/common/bin

While doing this, I noticed that there are some parts in the code, that will not be tree-shaken. Mainly global variables. Since the package.json states, that sideEffects: false I thought this might be of interest.

I collected some learning during the process, which might help: https://github.com/holtwick/zeed/tree/master/demos/sideeffects#readme

Anyway, the binary encoder you wrote is just great! 🎉

dmonad commented 1 year ago

Thanks @holtwick,

Thanks for the praise and the mention. Happy that the encoder is useful :)

There are indeed some variables that aren't tree-shaken. Mainly the console logger and the polyfills for node features.

When I wrote the code, NodeJs didn't support conditional exports yet. Now I can rewrite some parts by using conditional exports and make everything truly side-effect free.

holtwick commented 1 year ago

Awesome. I found "lazy initialization" particulary useful. In some areas like "logging" this is tricky, but it usually should work with only a small overhead.

You refer to the exports section in package.json like here? This is indeed very useful.

For my zeed project I decided to not further fragmentize the exports and have the tree shaking throw away everything unused instead of putting the work on the import side by deciding, which sub-package to use. Becoming side effect free also helped to eliminate some bugs I had, like for my logging on node, where I would request a file path globally that would have been used only in very rare cases.

An eslint plugin would be great to warn about such code, but I didn't find a good one 😉