microsoft / microsoft/TypeScript

erasableSyntaxOnly: support commonjs require/exports in .cts files

未关闭
#62,903 0 条评论 1 个 reaction 已指派 1 人 在 GitHub 查看

@andrewbranch 已经在做这个了。

开始于 2026年1月6日。

Needs Investigation
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

### 🔍 Search Terms

cts export

### ✅ Viability Checklist

- [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [x] This wouldn't change the runtime behavior of existing JavaScript code
- [x] This could be implemented without emitting different JS based on the types of the expressions
- [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [x] This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- [x] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals

### ⭐ Suggestion

Right now i can write (with type:module and allowJs:true):

module.cjs
```
module.exports.foo = 123;
```

index.ts
```
import { foo } from "./module.cjs"
```

and TypeScript correctly infers the type of the export `foo` (of course, it can have jsdoc types etc etc). Inside the .cjs file TS also correctly types result of `require()` calls.

However, if i do

module.cts
```
module.exports.foo = 123;
```

This no longer works. .cts file currently is supposed to have ESM style imports/exports that get transpiled to something.

However, such `module.cts` work perfectly fine with the `node` with type stripping - the types are stripped and the remaining code is processed as commonjs module (when package.json has type:module).

Suggestion - at least when erasableSyntaxOnly: true is specified, allow commonjs require/exports processing in .cts files, same as it happens in .cjs

### 📃 Motivating Example

This allows use of .cts files when escape from ESM to CJS is required in a project (for example, `require()` is needed to have conditional sync imports - yes, createRequire can be used in some cases, but not always).

It provides easier path to adopt typescript for node.js code when gradually converting existing codebases.

### 💻 Use Cases

1. What do you want to use this for?

to run .cts files directly in node with type stripping.

3. What shortcomings exist with current approaches?

we are forced to use .cjs with jsdoc type annotations, can't use .cts.

5. What workarounds are you using in the meantime?

using .cjs with type annotations.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。