我有一个JSON文件,看起来如下:
{
"primaryBright": "#2DC6FB",
"primaryMain": "#05B4F0",
"primaryDarker": "#04A1D7",
"primaryDarkest": "#048FBE",
"secondaryBright": "#4CD2C0",
"secondaryMain": "#00BFA5",
"secondaryDarker": "#009884",
"secondaryDarkest": "#007F6E",
"tertiaryMain": "#FA555A",
"tertiaryDarker": "#F93C42",
"tertiaryDarkest": "#F9232A",
"darkGrey": "#333333",
"lightGrey": "#777777"
}
我正试图将其导入到。tsx文件中。为此,我在类型定义中添加了如下内容:
declare module "*.json" {
const value: any;
export default value;
}
我像这样导入它。
导入颜色= require('../colors.json')
在文件中,我使用颜色primaryMain作为colors。primaryMain。但是我得到一个错误:
属性“primaryMain”在类型“*.json”中不存在
使用TypeScript 2.9。+你可以简单地导入JSON文件,这样做有类型安全和智能感知的好处:
import colorsJson from '../colors.json'; // This import style requires "esModuleInterop", see "side notes"
console.log(colorsJson.primaryBright);
确保在tsconfig的compilerOptions部分添加这些设置。json(文档):
"resolveJsonModule": true,
"esModuleInterop": true,
边注:
Typescript 2.9.0在这个JSON特性上有一个bug,它在2.9.2被修复了
esModuleInterop只对colorsJson的默认导入是必需的。如果你将其设置为false,那么你必须使用import * as colorsJson从'../colors.json'导入它
使用TypeScript 2.9。+你可以简单地导入JSON文件,这样做有类型安全和智能感知的好处:
import colorsJson from '../colors.json'; // This import style requires "esModuleInterop", see "side notes"
console.log(colorsJson.primaryBright);
确保在tsconfig的compilerOptions部分添加这些设置。json(文档):
"resolveJsonModule": true,
"esModuleInterop": true,
边注:
Typescript 2.9.0在这个JSON特性上有一个bug,它在2.9.2被修复了
esModuleInterop只对colorsJson的默认导入是必需的。如果你将其设置为false,那么你必须使用import * as colorsJson从'../colors.json'导入它