json - "resolveJsonModule"的用途?

标签 json typescript tsconfig

我引用的设置显示在下面的代码片段中

{
  "compilerOptions": {
    "resolveJsonModule": true,
  }
}

我不太明白为什么TS语言的工程师会为“resolveJsonModule”加个flag?环境要么支持通过 import 语句(或 require() 方法)将 JSON 解析为模块,要么环境不支持。为什么要为额外的复杂性烦恼?


最佳答案

上下文

从历史上看,Node 包含一个专门的 JSON 加载器(与 ECMA 标准无关)以允许导入 JSON 数据仅在 CommonJS 模式下

标准化导入任何东西(ES 模块)在 ECMAScript 中只是一个相对较新的现象。导入包含有效 JSON 的文本文件,解析为 native JS 数据(“导入 JSON”)在 a proposal that is still only in stage 3 中描述。 .

但是,最近在实现上述提案方面出现了一些变化:


typescript

TypeScript 是一个静态类型检查器,也是一个编译器(技术上是一个转译器),并将您的 TS 源代码语法转换为您在 TSConfig 中指定的运行时环境的有效 JavaScript 语法。因为不同的运行时环境具有不同的功能,所以您配置编译器的方式会影响发出的转换后的 JavaScript。关于默认值,编译器使用算法逻辑来确定设置。 (我无法在这里总结:老实说,您必须阅读整个 reference 才能理解它。)因为加载 JSON 数据一直是非标准的、专门的操作,直到最近,它才成为默认值。


备选方案

所有 JS 运行时都提供了 import 语句的替代方案,用于导入文本 JSON 数据(然后可以使用 JSON.parse 进行解析),并且它们都不需要配置编译器以您询问的方式:

Note: the data parsed from the JSON strings imported using these methods will not participate in the "automatic" type inference capabilities of the compiler module graph because they aren't part of the compilation graph: so they'll be typed as any (or possibly unknown in an extremely strict configuration).

Additionally, because all JSON (JavaScript Object Notation) is valid JS, you can simply prepend the data in your JSON file with export default , and then save the file as data.js instead of data.json, and then import it as a standard module: import {default as data} from './data.js';.


关于推断类型的最后说明:

我更喜欢审核我正在导入的 JSON 并使用我自己手动编写的数据类型(由我自己或其他人编写:从模块/声明文件导入),而不是依赖编译器的推断类型来自 import 语句(我发现它在很多情况下都太窄),通过使用 type assertion 将解析的 JSON 数据分配给一个新变量.

关于json - "resolveJsonModule"的用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71098595/

相关文章:

ios - 使用 AFNetworking 解析 JSON

c# - 将 .NET 对象序列化为 JSON

typescript - 如何包含排除文件夹中的文件/子文件夹?

typescript - Intellij 找不到 tsconfig.json

java - 将 Jackson json 属性映射到相应的 xml 元素

angular - 如何在 Angular 8 的抽象类和抽象类的实现中使用 @Component 装饰器?

javascript - 如何在动态加载的 Typescript 中扩展类

reactjs - 使用 TypeScript 在 create-react-app 中创建故事书

json - 在 Typescript : Error in terminal 中导入 Json 文件

json - Scala Play Json JSResultException 验证错误