I am quite new to JavaScript/Typescript in general and to JavaScript modules in particular.
I know there is tons of materials about my question in the web, but after reading for two days I feel I find many contradictions, maybe due to different articles created at different times, while things evolved. I’d be happy if somebody could clarify what’s the best way to go in mid of 2024.
My situation: I am about to write a typescript library, and now the question is in which form to deploy it. I was thinking about creating different versions for the CommonJS and for the ES module system, and additionally provide a bundled version in umd format, to be used locally in browsers (without the need of a web server).
I wanted to achieve this using tsc for the unpacked cjs and esm versions, and webpack for bundle a version in umd format.
This is where I got lost reading different documentation. I found an inspiring article here (https://evertpot.com/universal-commonjs-esm-typescript-packages/) which uses two different tsc configuration files for the unbundled cjs and esm versions, setting ‘module’ to ‘commonjs’ for the former and to ‘es2022’ for the latter. That sounded good to me. ‘moduleResolution’ would be set to ‘node10’ in both cases, as far as I can tell from the typescript docs (https://www.typescriptlang.org/tsconfig/#moduleResolution).
Now I read in the typescript docs (https://www.typescriptlang.org/docs/handbook/modules/guides/choosing-compiler-options.html#im-writing-a-library), if authoring a library, nowadays ‘module’ should be best set to either “node16” (or “nodenext”).
This opens a couple of questions for me:
-
Which one is the better way to go?
-
If using the ‘node16’ approach, would tsc transpile to ESM or CommonJS JavaScript?
-
And given that ‘node16’ should be the best ways, why does
tsc --init
generate a default tsc configuration file using ‘module’: ‘commonjs’? -
Is there still a need to care about CommonJS at all?
Finally, for the bundled ‘umd’ version, I’d use a tsconfig.json which uses 'module': 'nodenext'
, because webpack will anyway modify it, and use a webpack configuration file to output in ‘umd’ format? Any thoughts on this are of course also welcome.
Thanks you very much in advance