DEV Community

Discussion on: TypeScript 5.0: new mode bundler & ESM

Collapse
 
december1981 profile image
Stephen Brown • Edited

This is a very nice description, thanks.

Doesn't change the fact that modules are a stinking mess with javascript, and the weirdness with having to specify the .js extension in ts code is a reflection of that.

The decision by the nodejs people when they decided to natively support esm, to have to explicitly specify the extension for imports - as opposed to allowing it to resolve the file with some scheme like they did with commonjs: look for a file with ".js" if the import path does not explicitly specify an extension - makes no sense to me.

Their comment: "This behavior matches how import behaves in browser environments, assuming a typically configured server." is disingenuous, to say the least. Node isn't a browser environment, for crying out loud. It also makes it harder to use libraries exported from tsc, compiled to "module" setting es2020/esnext, etc - where there is no explicit import extension in the js output - understood in webpack environments where this file resolution is done by the transpiler when building the bundle, but would fall over if run directly in node (eg a cli tool running in the webpack application workspace which might use ts-node).

Collapse
 
designbyonyx profile image
Ryan Wheale • Edited

The javascript ecosystem is trying to create a module specification that works in virtually any environment. There are numerous benefits to this - mostly centering around interoperability and consistency between different environments.

The decision by the nodejs people ... to have to explicitly specify the extension for imports ... makes no sense to me.

It wasn't node.js that added the requirement for the file extension - it was the EcmaScript specification itself... which affects all JS. Node isn't copying the browser... they are implementing the spec. The old CommonJS algorithm for finding files was terribly inefficient and was largely a mistake (the creator of node admitted this mistake: youtu.be/M3BM9TB-8yA?t=835). By being explicit, JS runtimes don't have to look for the file... which is much faster and more explicit and affords a lot of other efficiencies. Adding typescript even compounds the problem: typescriptlang.org/docs/handbook/m...

As for the node REPL, it sucks it doesn't support ESM yet. I'm sure it will change soon. I generally use tsx to do most of my node REPL stuff - it's super fast and works with any flavor of JS or TS you are using.

If you are still writing code in CommonJS, I highly suggest you upgrade. You will be helping the community to move past CommonJS, and it is safe to do today. I just upgraded a large 6-year old codebase at a company who is resistant to change... and it went fairly smoothly once I got over the learning curve.