microsoft / microsoft/TypeScript
Suggestion: support Node `require` in ES Modules
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 2 T. 4 Std.
- Gemergte PRs (30 T.)
- 132
Beschreibung
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.
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit den Beispielen für bedingtes require im Issue und der verknüpften NodeRequireFunction-Deklaration in types/node/globals.d.ts. Es werden keine Repository-Dateien oder Tests genannt; als erledigt gilt die Typprüfung synchroner require-Aufrufe in ES-Modulen ohne die gezeigten Casts, wobei das ausgegebene JavaScript erhalten bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- node.js, typescript
- Bereich
- compilers
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 30/100