Microsoft/TypeScript

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

Open

#61.292 aberto em 26 de fev. de 2025

Ver no GitHub
 (2 comments) (0 reactions) (0 assignees)TypeScript (6.726 forks)batch import
BugDomain: Node ESMHelp Wanted

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

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

Guia do colaborador