记录在日常使用 ts 遇到的问题 & 解决方式
导入 json 文件
场景:项目中把配置存放到 json 文件,在模块中导入使用
问题:
- 使用 ESM 的方式导入模块报错
Consider using '--resolveJsonModule' to import module with '.json' extension. - 根据错误提示,设置
resolveJsonModule配置,出现新的错误提示This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.
解决:
- 在 tsconfig.json 配置的
compilerOptions字段中添加resolveJsonModule和esModuleInterop,值设置为 true
-
分析:
- ts 通过设置 resolveJsonModule , 允许导入带有 .json 扩展名的模块
- json 文件不处理导出 (类似 export default),通过 esModuleInterop 的配置,可以使用 ts 处理 json 文件的默认导入
-
参考