13

在我的 Angular 项目中,我正在为我自己的小型本地化服务导入 JSON 文件。我正在使用这里建议的方法,将我的更新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 之间发生了什么变化可能导致这种行为?

4

4 回答 4

20

事实证明,Angular 7 和 TypeScript 3.1实际上已经发生了一些变化(我猜他们从 TS 2.9+ 开始就已经存在了?)。使用问题中的代码,所有值都包含在“默认”对象中。为了防止这种情况,我不得不简化导入语句:

import de from './strings/de.json';
import en from './strings/en.json';

另请参阅此问题以获取有关如何在 TypeScript 中导入 JSON 文件的更多详细信息。

于 2018-10-19T09:11:45.757 回答
13

经过大量的挖掘和跟踪和错误,我终于让我的应用程序在 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.jsontypeRoots以使用src/typings.d.ts,例如:

    "typeRoots": [
      "node_modules/@types",
      "src/typings.d.ts"
    ],
    
  4. 导入 JSON:

    import data from './data.json';
    console.log(data);
    
于 2019-03-01T17:18:19.537 回答
7

在 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(阻止 ng lint 在 JSON 导入时中断)

这里唯一的变化是添加..."**/*.json"

"lint": {
  "builder": "@angular-devkit/build-angular:tslint",
  "options": {
    "tsConfig": [
      "src/tsconfig.app.json",
      "src/tsconfig.spec.json"
    ],
    "exclude": [
      "**/node_modules/**",
      "**/*.json"
    ]
  }
}
于 2019-04-29T18:05:29.557 回答
0

我正在寻找一种无需我修改 angular.json 文件即可工作的解决方案

我通过将我的 JSON 导出为 .ts 常量来解决它:

export const TEST_DATA = {...};

然后将其导入我的组件

于 2020-12-02T14:16:20.140 回答