hughsk / flat

:steam_locomotive: Flatten/unflatten nested Javascript objects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ERR_REQUIRE_ESM Add commonjs support

Alexnortung opened this issue · comments

If you try to use this library in a project that does not use ESM, it will give an error.

A solution would be to provide a commonjs version which can just be generated during CI.

Duplicate of #171

Okay, I see that it might be a duplicate, but the other issue was not solved either. Could you elaborate on why the other issue was marked as not planned? The library is not usable in projects that don't use ESM and providing a commonjs bundle would make this work.
I can help you set it up if you need it?

There are no plans to add support for CommonJS to this library, as that would increase the burden of maintenance. Specifically, it would mean that a build system needs to be introduced to compile the existing code to CommonJS.

It also means that we'd be shipping more code, further increasing the total size of the package. Aside from that, dual packing is a minefield and comes with a lot of strange interoperability bugs and gotchas, you can read all about it in this blog post (see also the links at the bottom).

The real problem here is how Node.js handles interoperability between CommonJS and ESM modules. Importing a CommonJS module from ESM works pretty well for the happy path, but importing ESM from CommonJS is messy, requiring you to make all your code async.

This is a problem unique to Node.js, other tools like bundlers (e.g. WebPack, Vite) do not suffer from this issue as they have taken an ESM-first approach. Even other run-times such as Bun allow you to mix import statements and require() calls freely.

My recommendation for anyone using Node.js right now would be to move to ESM for all your code as soon as possible, as this simply makes most of these problems go away. There are of course caveats such as Jest mocking working differently, and needing to load the entire module graph. But the fact is that standardized JavaScript modules are here, and they are the future of the ecosystem as a whole.