microsoft / microsoft/TypeScript

Suggestion: support Node `require` in ES Modules

未关闭
#29,976 7 条评论 4 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Search Terms

node require commonjs webpack conditional dynamic import

Suggestion

Node style require's are often used inside ES Modules for conditional imports. For example:

const getSentry = () => {
  if (__CLIENT__) {
    return require('./client-sentry').default;
  } else {
    return require('./server-sentry').default;
  }
};

export default getSentry();

In this example, require returns any as per the typings provide by @types/node.

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/5f59f3dc7a0965fb1767cf13c670c633bbbbf0a8/types/node/globals.d.ts#L190-L193

In order to acquire types, we have to use import types:

type ClientSentry = typeof import('./client-sentry');
type ServerSentry = typeof import('./server-sentry');

const getSentry = () => {
  if (__CLIENT__) {
    return (require('./client-sentry') as ClientSentry).default;
  } else {
    return (require('./server-sentry') as ServerSentry).default;
  }
};

export default getSentry();

I would like to suggest that TypeScript supports require calls inside of ES Modules (in Node envs). This way the workaround would not be necessary. Alternatively, perhaps TypeScript could make it possible for @types/node to improve the return type of require, e.g.

interface NodeRequireFunction {
    <Id extends string>(id: Id): typeof import(Id);
}

Note that require is desirable over dynamic imports because it is synchronous.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

贡献指南

打开贡献指南

从这里开始

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

调研方向

从 issue 中的条件 require 示例以及链接的 types/node/globals.d.ts 中的 NodeRequireFunction 声明开始。没有指定 repository 文件或测试;完成意味着能够在不使用所示 cast 的情况下对 ES 模块中的同步 require 调用进行类型检查,同时保持生成的 JavaScript 不变。

由索引模型根据 Issue 内容生成。

评估

技术栈
node.js, typescript
领域
compilers
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
30/100

把新 issue 发到你的邮箱

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