【问题标题】:require a json file results in an error: Cannot find module需要一个 json 文件导致错误:找不到模块
【发布时间】:2023-03-30 19:48:01
【问题描述】:

在启用了checkJs 的VsCode 中打开的nodej 项目中,当需要像

这样的json 文件时
const myFile = require('./my-file.json')

这会产生错误[ts] Cannot find module

如何消除错误警告?

我尝试过:

  1. "resolveJsonModule": true 添加到compilerOptions 中的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]

【问题讨论】:

  • 在进行 require 时不需要指定 json 扩展名。 const myFile = require('./my-file');
  • 谢谢,但如果没有扩展名,也会出现同样的错误。出现错误是因为 json 文件不是 module。 (-> 它没有module.exports)
  • 检查这个答案,也许它可以帮助你:stackoverflow.com/questions/49996456/…

标签: javascript json typescript visual-studio-code checkjs


【解决方案1】:

你应该添加

"resolveJsonModule":true

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

【讨论】:

    【解决方案2】:

    我在尝试从 typescript 项目中的文件导入 json 时遇到了类似的问题。

    我用过

    import * as data from "module/path/filename.json"
    

    而不是

    const data = require("module/path/filename.json")
    

    它成功了。

    【讨论】:

    • 这只是给了我“不能在模块外使用 import 语句”
    猜你喜欢
    • 2015-04-10
    • 2018-12-24
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2022-01-13
    • 2022-08-07
    • 2021-03-31
    • 1970-01-01
    相关资源
    最近更新 更多