resolveJsonModule 在 Angular 10 中不起作用?

Mel*_*how 13 typescript angular angular10

我在一个全新的 Angular 10 项目的资产文件夹中有一个基本的 JSON 文件。
Angular CLI:10.0.1 节点:14.5.0 操作系统:win32 x64 TSC 版本 3.9.5。在我的 tsconfig.json 我有

  "compilerOptions": {
    "module": "commonjs",
    "resolveJsonModule": true,
    "esModuleInterop": true
  }
Run Code Online (Sandbox Code Playgroud)

I have restarted vscode multiple times, and tried compiling from the vscode terminal, a powershell window, and a bash terminal, all returning the same message: "Consider using '--resolveJsonModule' to import module with '.json' extension". I have tried compiling with multiple combinations of different options. At this point I'm wondering if I should restart this project and simply downgrade my version of Angular?

小智 17

在 Angular 版本 10 中,我们有 3 个“tsconfig”文件。

您必须在“compilerOptions”内的“tsconfig.app.json”文件中添加“resolveJsonModule”和“esModuleInterop”选项。

该文件应如下所示:

{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)


小智 11

如果有人在 Angular 11 中有类似的东西:

我收到了这个额外的错误信息:

找不到模块“nameOfMyJsonFile.json”。考虑使用“--resolveJsonModule”导入带有“.json”扩展名的模块。

所以,我不得不添加resolveJsonModule“tsconfig.json”文件中compilerOptions,而不是在tsconfig.app.json

 {
      "compileOnSave": false,
      "compilerOptions": {
        "baseUrl": "./",
        "outDir": "./dist/out-tsc",
        "resolveJsonModule": true,
        "sourceMap": true,
        "declaration": false,
        "downlevelIteration": true,
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "importHelpers": true,
        "target": "es2015",
        "module": "es2020",
        "lib": [
          "es2018",
          "dom"
        ]
      }
    }
Run Code Online (Sandbox Code Playgroud)


ir0*_*r0h 10

我在运行 Ionic 5 (Angular 12) 测试时遇到了同样的问题。解决了它:

import * as SomeJsonObjectName from './assets/someObject.json
Run Code Online (Sandbox Code Playgroud)

但只有在添加之后

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

到tsconfig.json 的编译器选项

  • 在没有 `"esModuleInterop": true` 的情况下为我工作 (2认同)