【问题标题】:Importing json file in typescript 2.9.2 and Angular 6 app is not working在 typescript 2.9.2 和 Angular 6 应用程序中导入 json 文件不起作用
【发布时间】:2019-08-08 19:04:10
【问题描述】:

我正在运行一个 Angular 6 应用,使用这个版本的打字稿:"typescript": "~2.9.2"

我跟着this answer 在 typescript 2.9.* 中导入 json 文件,但它不起作用。

这是我的tsconfig.json 文件:

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

然后是我要导入的app.component.ts 文件:

import * as config from '../../config.json';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit, OnDestroy {

但我得到了错误:

error TS2497: Module '"C:/Users/..../config"' resolves to a non-module entity and cannot be imported using this construct.

【问题讨论】:

  • 我对 Angular 不熟悉,但你试过 import config from '../../config.json'; 吗?
  • @Striped 现在我得到:...has no default export
  • 我看到了,有帮助吗? angularjswiki.com/angular/…
  • 有一个区别,tsconfig.json 文件中的"esModuleInterop": true 允许从没有默认导出的模块默认导入。

标签: json angular typescript


【解决方案1】:

我使用"allowSyntheticDefaultImports": true 来完成这项工作,并使用import version from './package.json'。 根据文档,合成导入允许从没有默认导出的模块默认导入。这不会影响代码发出,只是类型检查。使用它,我不再遇到您提到的错误。

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 2019-01-23
    • 2019-05-17
    • 2023-03-24
    • 2017-12-09
    • 2017-11-16
    • 2018-12-03
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多