dmonad / lib0

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

add conditional exports #23

Closed philippkuehn closed 3 years ago

philippkuehn commented 3 years ago

Hey, with this PR the library is working fine for me when using esm or cjs.

Sidenote: A bit strange that I had to put .cjs in the export keys, but otherwise it didn't work. Do you know why?

dmonad commented 3 years ago

I write all my modules in ESM and point to lib0/[name].js. When building the CJS files, I replace all ESM locations to the respective CJS version. Library modules like y-protocols and lib0 follow the pattern that lib0/[name].js is the ESM version and lib0/dist/[name].cjs is the CJS version. You can find my transpilation step here: https://github.com/yjs/yjs/blob/baca852733eaa0c2b0b3cb5d30972418c356a47f/rollup.config.js#L31

It would be easy to add the same configuration step for webpack.

That said, you can of course also make use of the conditional exports feature (which is well supported by nodejs, but not yet by all module bundlers).

When implementing the conditional exports feature I thought we would point from lib0/[name] to either lib0/[name].js (if module) or lib0/dist/[name].cjs (if commonjs). At least that is the pattern that is recommended in the nodejs documentation: https://nodejs.org/api/packages.html#packages_conditional_exports

"./dist/array.cjs": {
   "import": "./array.js",
   "require": "./dist/array.cjs"
 },

This is a bit non-idiomatic because you would expect to consume the commonjs module when importing lib0/dist/array.cjs.

I'm counting the days for the day when Node v10 is deprecated. Then I can finally put all these dependencies in a separate folder and make the use of conditional exports (which are supported in node >=v12).

If the conditional exports patterns works for you better than rewriting dependency-locations as I do, we can implement the same pattern in all Yjs-related modules. Just open a separate ticket in the yjs repo.

dmonad commented 3 years ago

Oh, sorry for this wall of text. Could you explain why you point from /dist/[name].cjs to the respective files and not from /[name]?

philippkuehn commented 3 years ago

Get it now! ! will just stick with the esm modules! future! 💪