在Angular 7项目中导入JSON

Tho*_*mas 10 json angular angular7

在我的Angular项目中,我正在为我自己的小本地化服务导入JSON文件.我正在使用此处建议的方法,将我更新typings.d.ts

declare module "*.json" {
    const value: any;
    export default value;
}
Run Code Online (Sandbox Code Playgroud)

这适用于Angular 6,但在更新到Angular 7后,当我尝试访问属性时,我的导入似乎未定义.

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

var s = en["mykey"]
Run Code Online (Sandbox Code Playgroud)

JSON有一个非常简单的key => value结构:

{
  "myKey": "My Headline",
  …
}
Run Code Online (Sandbox Code Playgroud)

6.1和7之间有什么变化可能会导致这种行为?

Tho*_*mas 14

事实证明,Angular 7和TypeScript 3.1 实际上已经有了一些变化(我猜他们已经存在,因为TS 2.9+?).使用问题中的代码,所有值都包含在"default"对象中.为了防止这种情况,我必须简化import语句:

import de from './strings/de.json';
import en from './strings/en.json';
Run Code Online (Sandbox Code Playgroud)

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


Gre*_*own 9

经过大量的挖掘,跟踪和错误之后,我终于有了我的应用程序,可以在Angular 7中正确导入JSON:

  1. 首先,删除

    "resolveJsonModule": true
    "esModuleInterop": true
    
    Run Code Online (Sandbox Code Playgroud)

    tsconfig.json中获取,如果您从其他非Angular 7特定答案中获取。

  2. 创建src / typings.d.ts

    declare module "*.json" {
      const value: any;
      export default value;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 更新typeRootstsconfig.json到使用的src / typings.d.ts,如:

    "typeRoots": [
      "node_modules/@types",
      "src/typings.d.ts"
    ],
    
    Run Code Online (Sandbox Code Playgroud)
  4. 导入JSON:

    import data from './data.json';
    console.log(data);
    
    Run Code Online (Sandbox Code Playgroud)


dan*_*y74 6

在Angular 7中,我必须采取以下步骤:

(1)进口

import pkg from '../../package.json'
Run Code Online (Sandbox Code Playgroud)

(2)tsconfig.json

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    AND more compiler options here
  }
}
Run Code Online (Sandbox Code Playgroud)

(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"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)