2 min

The new release features ECMAScript Module Support in Node.js and more.

Microsoft announced the launch of the TypeScript 4.7 beta which includes ECMAScript Module Support in Node.js, control over module detection, control-flow analysis for computed properties, and more. 

In TypeScript 4.5, Microsoft added nightly-only support for ESM in Node.js to get some feedback from users and let library authors ready themselves for broader support. TypeScript 4.7 expands this functionality with two new ‘module’ settings: ‘node12’ and ‘nodenext’.

The new setting controls whether ‘.js’ files are interpreted as ES modules or CommonJS modules, and defaults to CommonJS when not set.

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.”

Splitting between ES and 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 difficult. 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.

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

The beta release was announced in a blog post by Daniel Rosenwasser, the Senior Program Manager for TypeScript. “In the coming weeks, we’ll be polishing TypeScript 4.7 to get it ready for a Release Candidate,” he writes. They will also be “making sure that everything works just as you would expect.”

Also read: Microsoft presents final release of TypeScript 4.6.