【问题标题】:Import .json files into Angular - "resolves to a non-module entity and cannot be imported using this construct."将 .json 文件导入 Angular -“解析为非模块实体,无法使用此构造导入。”
【发布时间】:2019-01-29 13:51:55
【问题描述】:

我正在尝试将 .json 文件导入 angular 的 typescript 文件中。

import * as languagesData from './../../data/languages.json';

上面的导入语句给出以下错误:

untouchable-app/library/data/languages"' 解析为非模块 实体,无法使用此构造导入。

文件夹结构。

library/
projects/
node_modules/
tsconfig.json
typings.d.ts

我已经更新到打字稿版本2.9.2

package.json

"devDependencies": {
    "typescript": "^2.9.2"
}

typings.d.ts

declare module "*.json" {
    const value: any;
    export default value;
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "resolveJsonModule": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "paths": {
      "library": [
        "library/"
      ],
      "library/*": [
        "library/*"
      ]
    }
  }
}

library/services/report/report.service.ts

import * as languagesData from './../../data/languages.json';

projects/project-name/src/app/app.component.ts

import { ReportService } from 'library/services/report/report.service';

注意

我有一个“库”文件夹,其中包含可以在我的项目文件夹中包含的多个应用程序之间共享的常用组件和服务。我正在将库中的服务导入我的应用程序。服务文件是包含对 json 数据的导入语句的文件。

【问题讨论】:

标签: angular typescript


【解决方案1】:

尝试将以下内容添加到您的 tsconfig.json:

  "compilerOptions": {
     ...
     "esModuleInterop": true,
     ...
  }

然后以这种方式导入你的 json 文件:

import languagesData from './../../data/languages.json';

这对我有用(Angular 6,带有 Angular cli)。

【讨论】:

    猜你喜欢
    • 2016-05-18
    • 2017-12-12
    • 2017-01-17
    • 2017-07-11
    • 2020-06-30
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 2020-05-25
    相关资源
    最近更新 更多