TypeScript 4.7 bêta

Microsoft announced the availability of TypeScript 4.7 beta. The major contribution of this new version is the support of the ECMScript module in node.js.

For a few years, Node.js has been working to support ECMAScript (ESM) modules. This is a very difficult topic, because the Node.js ecosystem is built on a different module system called CommonJS (CJS). Interoperability between the two brings great challenges, with many new features to juggle; however, ESM support in Node.js has been largely implemented in Node.js 12 and later. Since TypeScript 4.5, Microsoft has rolled out nightly support only for ESM in Node.js to get user feedback and allow library authors to prepare for broader support.

TypeScript 4.7 adds this functionality with two new module parameters: node12 and nodenext.

{
“compilerOptions”: {
“module”: “nodenext”,
}
}

Another new feature worth noting is the module detection control. One problem with the introduction of modules into JavaScript was the ambiguity between existing “script” code and new module code. JavaScript code in a module executes slightly differently and has different scoping rules, so tools must make decisions about how each file executes. For example, Node.js requires module entry points to be written in a .mjs, or have package.json nearby with “type”: “module”. TypeScript treats a file as a module whenever it finds an import or export statement in a file, but otherwise it will assume that a .ts or .js file is a script file acting on the global scope

This doesn’t quite match the behavior of Node.js where the package.json can modify the format of a file, or the –jsxreact-jsx parameter, where a JSX file contains an implicit import to a JSX factory. It also doesn’t live up to modern expectations where most new TypeScript code is written with modules in mind.

This is why TypeScript 4.7 introduces a new option called moduleDetection. moduleDetection can take 3 values: “auto” (the default value), “legacy” (the same behavior as version 4.6 and earlier), and “force”.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.