microsoft / microsoft/TypeScript
strange interaction with `resolveJsonModule`, `createRequire`, naming it `require`, and requiring JSON
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
### 🔎 Search Terms
esm resolveJsonModule
### 🕗 Version & Regression Information
This isn't reproducible in the playground because the TSConfig editor, unlike in reality, doesn't allow you to configure `resolveJsonModule` when module is NodeNext.
### ⏯ Playground Link
n/a
### 💻 Code
Here's my config:
```
{
"extends": "@ljharb/tsconfig", // this sets resolveJsonModule to true
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
},
"exclude": [
"coverage",
],
}
```
`@ljharb/tsconfig` sets `resolveJsonModule` to `true`.
Here's my code:
```
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
require('./package.json');
```
### 🙁 Actual behavior
When `resolveJsonModule` is locally omitted or set to `true`, I get `error TS6133: 'require' is declared but its value is never read.` on the `const require =` declaration.
When it's locally set to `false`, I get that error AND `error TS2732: Cannot find module '../package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.` on the `require()` call.
However, when I rename it from `require` to literally anything else, the errors disappear for all three config variations.
### 🙂 Expected behavior
I should be able to name a variable `require` in an ES Module without it having any implied semantics, since `require` only exists by default in CJS.
### Additional information about the issue
_No response_
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 provided NodeNext configuration and the code using createRequire(import.meta.url), then reproduce the diagnostics with resolveJsonModule omitted, enabled, and disabled. Compare those results with the same code after renaming the local require variable; done means the variable name no longer changes unused-variable or JSON-module diagnostics in an ES module.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100