Isn't ESM the "way forward" for Node.js? I've seen tons of posts a out how TypeScript allows use of modules, and that's always seen as a good thing, but then discussion of ESM always seems to be met with disdain.
If you use typescript you don't even have to do anything.
I've converted a few medium-sized Typescript projects from CJS to ESM.
Unfortunately, TypeScript still has some issues with Node & ESM. Notably, many popular CommonJS packages don't work with named imports such as import { foo } from 'bar'. You have to do import bar from 'bar' and then use it like bar.foo() or destructure it like const { foo } = bar. However, typescript won't tell you this at all. The broken import will not only compile fine, TypeScript will actually suggest it via auto-imports.
Also, modules in ESM require the .js extension - import foo from './bar' is invalid. But even if your project uses ESM, TypeScript's auto-imports will default to not using an extension. Again, it suggests and compiles code that immediately fails at runtime.
The second issue is apparently going to be improved in an upcoming release, but there's no solution in sight for the first issue.
Neither of these are the end of the world, but it means that converting a CommonJS codebase written in TS isn't as simple as changing a couple config flags, and the development experience post-conversion is noticeably more frustrating. And unless you want to use top-level await, you don't actually gain anything in exchange for this frustration. Except for the fact that some popular modules are dropping CJS support.
ESM may be the way forward, but at the moment it feels like a step backwards in terms of dev experience.
62
u/Zipdox Feb 01 '22
Now we can finally ditch node-fetch, which I've wanted to do ever since it switched to ESM.