Microsoft/TypeScript

strange interaction with `resolveJsonModule`, `createRequire`, naming it `require`, and requiring JSON

Open

#61 292 ouverte le 26 févr. 2025

Voir sur GitHub
 (2 commentaires) (0 réactions) (0 assignés)TypeScript (6 726 forks)batch import
BugDomain: Node ESMHelp Wanted

Métriques du dépôt

Stars
 (48 455 stars)
Métriques de merge PR
 (Merge moyen 6j 17h) (9 PRs mergées en 30 j)

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

Guide contributeur