从 JSON 模块正确导入默认导出

诺蒙德·卡恩贝辛斯

我的 Angular 应用程序中有一个 JSON 翻译文件“./countries/es.json”,我想导入并循环遍历。

{
...
"Solomon Islands": "Islas Salomón",
"South Sudan": "Sudán del Sur",
...
}

我有"resolveJsonModule": true,我的tsconfig.json文件,所以总的来说导入很顺利。

import * as countries from './countries/es.json';

如果我访问该对象,请说countries['Solomon Islands']我得到正确的“Islas Salomón”。

但是,如果要枚举所有国家/地区:

const countries_keys = Object.keys(countries);

country_keys是一个具有一个值“默认”的数组。为了获得国家名单,我需要做:

const countries_keys = Object.keys(countries['default']);

我的问题 - 有没有办法干净地进行导入,以便我完全按照 JSON 文件中的方式获取对象?

如果我有这样的源文件:

{
countries: {
    ...
    "Solomon Islands": "Islas Salomón",
    "South Sudan": "Sudán del Sur",
    ...
    }
}

我可以简单地做:

import  { countries } from './countries/es.json';

但是有没有一种干净的方法可以将我的原始文件作为等效的 JSON 对象导入而无需额外的“默认”属性。

李宣

你需要allowSyntheticDefaultImports在你的tsconfig.json.

tsconfig.json

{
  "allowSyntheticDefaultImports": true,
  "resolveJsonModule": true
}

TS

import countries from './countries/es.json';

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章