在Angular 7项目中导入JSON

问题描述 投票:8回答:3

在我的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之间有什么变化可能会导致这种行为?

json angular angular7
3个回答
14
投票

结果是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文件。


4
投票

经过大量的挖掘和反复试验,我终于让我的应用程序在Angular 7中正确导入JSON:

  1. 首先,删除 "resolveJsonModule": true "esModuleInterop": true 来自tsconfig.json,如果你有其他非Angular 7特定答案。
  2. 创建src / typings.d.ts: declare module "*.json" { const value: any; export default value; }
  3. 更新tsconfig.json中的typeRoots以使用src / typings.d.ts,例如: "typeRoots": [ "node_modules/@types", "src/typings.d.ts" ],
  4. 导入JSON: import data from './data.json'; console.log(data);

4
投票

在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"
    ]
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.