Angular 8和导入Json

38

我读过几篇文章说自从 type script 2.9 版本之后,现在可以直接导入 JSON 格式文件了。因此,我已经修改了我的 tsconfig.json 文件如下:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  },
  "paths": {
    "@data/*": ["src/core/data/*"],
    "@models/*": ["src/core/models/*"],
    "@services/*": ["src/core/*"],
    "@environments/*": ["src/environments/*"]
  },
  "resolveJsonModule": true,
  "esModuleInterop": true,
  "allowSyntheticDefaultImports": true
}

然后我像这样将json导入到我的组件中:

import particlesJson from '../../assets/particles.json';

程序运行正常,但控制台中出现了一个错误:

ERROR in src/app/profile/login.component.ts(3,27): error TS2732: 找不到模块'../../assets/particles.json'。请考虑使用“--resolveJsonModule”导入带有“.json”扩展名的模块

我该如何避免这个错误的出现?


你正在使用的 TypeScript 版本是什么? - abd995
5个回答

77
"resolveJsonModule": true,
"esModuleInterop": true,

根据文档,应该将其放置在tsconfig.jsoncompilerOptions下。
请参见此处的示例


5
这个对每个人都有效吗?如果对我不起作用,我该如何理解问题所在?我使用 Angular 10,即使重新启动“一切”,我也无法导入 { version } from '../../../package.json';我仍然遇到同样的错误:考虑使用“--resolveJsonModule”来导入带有“.json”扩展名的模块.ts(2732) - Budda
@DavideQuaglio 奇怪。虽然我没有仓库再试一次,但你确定你正在编辑正确的 tsconfig 文件吗? - LppEdd
@LppEdd 我认为问题在于这种方法只有在构建应用程序时才读取文件,而不是在运行时读取,对吗? - Davide Quaglio
@DavideQuaglio 是的。这在编译时起作用。但这严格与TypeScript相关。就运行时而言,它并不会改变任何东西,因为我们仍然在使用JavaScript。 - LppEdd
1
解决JSON问题。然而,无论我在哪里导入moment,如“import * as moment from 'moment';”,编译都会失败,并显示“Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead”。使用require也无法解决此问题。@LppEdd请再次检查您的答案。 - Ren
在 Angular 8 中,"resolveJsonModule": true,我认为已经足够了。 - harsha kumar Reddy

25

在我的情况下,好老的计算机科学方法奏效了,只需重新启动Visual Studio Code即可。


3
经过数小时的调试,你的评论对我很有帮助。重新启动加载tsconfig文件可以使它工作。 - Aditya Mittal

1

即使使用了文档中的LppEdd解决方案,我唯一的解决办法是添加// @ts-ignore,然后我才能成功获取json文件。

版本:8


0
我这边的问题是在"compilerOptions"部分找不到"resolveJsonModule"。

0

在 Angular 8+ 中,如果以下内容正确,则可以使用:

"resolveJsonModule": true, 
"esModuleInterop": true,

在 tsconfig.add.json 和 tsconfig.json 中都有。 我猜测不需要重新启动 VS Code,但有时需要一些时间让 vscode 采用新的 ts 规则。


2
@LppEdd已经回答了,请不要再发相同的答案。 - Raphaël Balet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接