Microsoft/TypeScript

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

Open

#61,292 创建于 2025年2月26日

在 GitHub 查看
 (2 评论) (0 反应) (0 负责人)TypeScript (6,726 fork)batch import
BugDomain: Node ESMHelp Wanted

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

🔎 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

贡献者指南