需要一个 json 文件导致错误:找不到模块

Fra*_*ain 18 javascript json visual-studio-code checkjs

checkJs启用了 VsCode 的 nodej 项目中,当需要 json 文件时,例如

const myFile = require('./my-file.json')
Run Code Online (Sandbox Code Playgroud)

这会导致错误[ts] Cannot find module

如何消除错误警告?

我试过了:

  1. 添加"resolveJsonModule": truecompilerOptionsin jsconfig.json,但它不起作用。

  2. 创建一个typing.d.ts包含以下内容的文件:

    declare module '*.json' { const value: any; export default value; } 但是现在出现了一个错误 [ts] Type 'typeof import("*.json")' must have a '[Symbol.iterator]()' method that returns an iterator. [2488]

gvl*_*sov 6

尝试从打字稿项目中的文件导入 json 时,我遇到了类似的问题。

我用了

import * as data from "module/path/filename.json"
Run Code Online (Sandbox Code Playgroud)

代替

const data = require("module/path/filename.json")
Run Code Online (Sandbox Code Playgroud)

它奏效了。

  • 这只是给了我“不能在模块外部使用 import 语句” (6认同)

小智 5

你应该添加

"resolveJsonModule":true

作为tsconfig.json的compilerOptions 的一部分。