简体   繁体   English

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

[英]require a json file results in an error: Cannot find module

In a nodej project open in VsCode with checkJs enabled, when a json file is required like在nodej项目在VsCode开放checkJs启用,当需要一个JSON文件中像

const myFile = require('./my-file.json')

This makes an error [ts] Cannot find module .这会导致错误[ts] Cannot find module

How is it possible to remove the error warning?如何消除错误警告?

I tried to:我试过了:

  1. add "resolveJsonModule": true to the compilerOptions in jsconfig.json , but it does not work.添加"resolveJsonModule": truecompilerOptionsjsconfig.json ,但它不工作。

  2. create a typing.d.ts file with this content:使用以下内容创建一个typing.d.ts文件:

    declare module '*.json' { const value: any; export default value; } declare module '*.json' { const value: any; export default value; } But now, there is an error [ts] Type 'typeof import("*.json")' must have a '[Symbol.iterator]()' method that returns an iterator. [2488] 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] [ts] Type 'typeof import("*.json")' must have a '[Symbol.iterator]()' method that returns an iterator. [2488]

I had a similar problem when trying to import json from a file in a typescript project.尝试从打字稿项目中的文件导入 json 时,我遇到了类似的问题。

I used我用了

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

instead of代替

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

and it worked.它奏效了。

You should add你应该添加

"resolveJsonModule":true

as part of compilerOptions to tsconfig.json.作为 tsconfig.json 的compilerOptions 的一部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:找不到模块 './config.json' 需要堆栈:[...] {JS} - Error: Cannot find module './config.json' Require stack: [...] {JS} 错误:找不到模块“data.json”需要堆栈:-C: - Error: Cannot find module 'data.json' Require stack: - C: 反应并要求:错误:找不到模块“。” - React & require: Error: Cannot find module “.” 找不到模块“需要” - Cannot find module 'require' 运行 Babel 转译代码时需要 JSON 文件引发 Node.js 加载程序错误“错误:找不到模块'example.json'” - require a JSON file throws a Node.js loader error "Error: Cannot find module 'example.json'" when running Babel transpiled code Node.js:尝试要求使用Unirest模块时找不到模块错误 - Nodejs: Cannot find module error while trying to require unirest module 使用 JSON 文件在 VueJS 错误中找不到模块 - Cannot find module in VueJS Error using a JSON file 尝试要求我的javascript文件时找不到模块“ models / PermissionModel”错误 - Cannot find module 'models/PermissionModel' error when I try to require my javascript file 如何在require(&#39;./ <path to json from working directory> &#39;)抛出错误:找不到模块&#39;./ <path to json> &#39;? - How to fix this issue where require('./<path to json from working directory>') is throwing ERROR: Cannot find module './<path to json>'? 安装帮助程序文件的节点模块在安装时导致“找不到模块”错误 - Node module with Helper file results in 'cannot find module' error when installed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM