microsoft / microsoft/TypeScript

Suggestion: support Node `require` in ES Modules

オープン
#29,976 コメント 7 件 リアクション 4 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

In Discussion Suggestion
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
2日 4時間
マージ済み PR(30日)
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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Issue の条件付き require の例と、リンクされている types/node/globals.d.ts の NodeRequireFunction 宣言から始めます。リポジトリのファイルやテストは指定されていません。完了とは、示されているキャストなしで ES モジュール内の同期的な require 呼び出しを型チェックでき、生成される JavaScript を維持できることを意味します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
node.js, typescript
領域
compilers
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
30/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。