在我的Angular项目中,我正在为我自己的小本地化服务导入JSON文件。我正在使用the method suggested here,将我的typings.d.ts
更新为
declare module "*.json" {
const value: any;
export default value;
}
这适用于Angular 6,但在更新到Angular 7后,当我尝试访问属性时,我的导入似乎未定义。
import * as de from './strings/de.json';
import * as en from './strings/en.json';
var s = en["mykey"]
JSON有一个非常简单的key => value结构:
{
"myKey": "My Headline",
…
}
6.1和7之间有什么变化可能会导致这种行为?
结果是Angular 7和TypeScript 3.1 there actually have been some changes(我猜他们自TS 2.9+以来一直在那里?)。使用问题中的代码,所有值都包含在“default”对象中。为了防止这种情况,我必须简化import语句:
import de from './strings/de.json';
import en from './strings/en.json';
Also see this question for more details关于如何在TypeScript中导入JSON文件。
经过大量的挖掘和反复试验,我终于让我的应用程序在Angular 7中正确导入JSON:
"resolveJsonModule": true
"esModuleInterop": true
来自tsconfig.json,如果你有其他非Angular 7特定答案。declare module "*.json" {
const value: any;
export default value;
}
typeRoots
以使用src / typings.d.ts,例如:
"typeRoots": [
"node_modules/@types",
"src/typings.d.ts"
],
import data from './data.json';
console.log(data);
在Angular 7中,我不得不采取以下步骤:
(1)进口
import pkg from '../../package.json'
(2)tsconfig.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"resolveJsonModule": true,
AND more compiler options here
}
}
(3)angular.json(停止在JSON导入上打破lint)
这里唯一的变化是添加... "**/*.json"
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**",
"**/*.json"
]
}
}