Support for ECMAScript modules in Node.js • DEVCLASS

The TypeScript team has just released the 4.7 beta. The biggest new feature is the inclusion of support for ECMAScript modules in Node.js, which has been in the nightly (early adopter) builds of TypeScript since version 4.5.

The split between the official ECMAScript (ES) approach to modules and that of the earlier CommonJS convention is a painful one. ES modules have native browser support (other than in Internet Explorer) whereas CommonJS requires transpiling. Although there is consensus that ES6 modules are the way forward, CommonJS is deeply embedded in the industry, not least in Node.js, despite efforts to introduce ES6 compatibility since Node 12.

TypeScript has long supported ES6 modules but the issue being addressed is how to give the TypeScript compiler first-class support for Node when Node is used with ES6 modules. Two new compiler option settings, “nodenext” and “node12” integrate with Node’s options. There are also new source file extensions for TypeScript, .mts and .cts, which compile to .mjs and .cjs, with .mjs meaning “always treat as a module” and .cjs meaning “always treat as CommonJS.” There is also a change to TypeScript’s module detection for .ts files. Previously this just looked for import and export statements, where now, in the new mode, it will also check the package.json file used to define Node packages, and also inspect whether a file is a React JSX (JavaScript Extension).

The split between the official ECMAScript (ES) approach to modules and that of the earlier CommonJS convention is a painful one

These features are important for advancing ES6 usage but the intricacies of TypeScript and JavaScript modules are also a burden on developers.

“I despair at the direction of native esmodules. CommonJS with transpiled ESM behaves in a completely sane way for any developer from any ecosystem, and supports things like mocking. ESModules are going to be our python 3,” said one dissenting developer on Reddit.

Module support is not the only thing changing in TypeScript 4.7. There is also improved inference of type from functions within objects and arrays, a clever thing called Instantiation expressions that simplifies coding specialised instances of generic functions, and more.

Instantiation expressions in TypeScript 4.7, in the TypeScript Playground

TypeScript releases follow a two-monthly pattern. The current plan is to release 4.7 RC in one month, on May 10th, and the full release on May 24th.

Source link


Leave a Reply

Your email address will not be published. Required fields are marked *