microsoft / microsoft/TypeScript

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

未关闭
#61,292 3 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Bug Domain: Node ESM Help Wanted Needs Human Review Needs More Info
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

🔎 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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从提供的 NodeNext 配置以及使用 createRequire(import.meta.url) 的代码开始,然后分别在省略、启用和禁用 resolveJsonModule 的情况下复现诊断结果。将这些结果与重命名本地 require 变量后的相同代码的结果进行比较;当变量名不再改变 ES 模块中的未使用变量或 JSON 模块诊断时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
typescript
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
活跃
描述清晰度
基本清楚
新手友好度
48/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。