microsoft / microsoft/TypeScript
Suggestion: support Node `require` in ES Modules
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the issue's conditional require examples and the linked types/node/globals.d.ts NodeRequireFunction declaration. No repository files or tests are named; done would mean type-checking synchronous require calls in ES modules without the shown casts while preserving emitted JavaScript.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- node.js, typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100