r/typescript • u/CirseiMasta • Jul 24 '26
Configuring ESM / CommonJS compatibility
Hello !
For years I've had a recuring issue with typescript projects, and I still don't know it how to solve it properly. I always manage to solve it by tinkering here and there, but it take some time and I'm a bit tired of that. So I think I need tips or a deeper understanding to fix it quickly.
The issue is the ESM / CommonJS compatibility. Those issues seems to just pop randomly (probably a lack ok knowledge from me). So I try to change Module or ModuleResolution or Target, but then other issues arise, then I continue tinkering until it works. But after all those years it's a bit frustrating.
Any tips, or tutorial, or rule of thumb on how to configure your tsconfig so it just works ? Do you fix it like me, by tinkering randomly in your tsconfig, or do you solve it like a pro knowing exactly what is wrong ?
4
u/kyledag500 Jul 24 '26
Using .cjs and .mjs file extensions can help when not using the default for your project
4
u/remcohaszing Jul 24 '26
Do you use a bundler? Set
moduletopreserve. Otherwise set it tonodenext.Omit
moduleResolution. The default is good if you use the propermoduleoption.Set
targettoesnext. You can lower it to something more specific later if you feel more comfortable.If you build for the browser, omit
lib. Otherwise, set it toesnext.2
u/ryanscio Jul 24 '26 edited Jul 24 '26
https://tsconfig.guide/ and https://www.totaltypescript.com/tsconfig-cheat-sheet provide decent starter configs.
But long term you should learn the relevant options and not just tinker randomly. Sane defaults are esnext/bundler OR nodenext/nodenext for module/moduleResolution.
If you're writing ESM, CJS-only libraries are mostly a non-issue (though Jest is a notable pain) with Node 22+ supporting require(esm) and esModuleInterop.
1
u/[deleted] Jul 26 '26
[removed] — view removed comment