【问题标题】:Cannot find module 'mongoose' with typeScript无法使用 typeScript 找到模块 \'mongoose\'
【发布时间】:2022-11-22 13:33:09
【问题描述】:

我想在顶级函数中使用 await,为此 typeScript 要求我将我的目标语言放入 tsconfig.json 到 2017 年或更高版本,并将模块放入 es2022。但是当我这样做时,出现了这个错误:“找不到模块‘mongoose’。您是要将‘moduleResolution’选项设置为‘node’,还是要为‘paths’选项添加别名?”

我已经在很多地方进行了搜索,但没有找到解决方案。

这是我的一些代码:

tsconfig.json

{
"compilerOptions": {
 "target": "es2022",   
"module": "es2022",
"outDir": "./build",     
"esModuleInterop": true,   
 "forceConsistentCasingInFileNames": true,
 "strict": true,  
"skipLibCheck": true 
}
}

包.json

{
  "name": "finanzas",
  "version": "1.0.0",
  "description": "API que permite gestionar las finanzas de un nucleo familiar o individuo",
  "main": "index.js",
  "scripts": {
    "dev": "ts-node-dev src/index.ts",
    "start": "node build/index.js",
    "tsc": "tsc",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Andres Felipe Cuervo",
  "license": "ISC",
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/mongoose": "^5.11.97",
    "@types/node": "^17.0.44",
    "dotenv": "^16.0.1",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.7.3"
  },
  "dependencies": {
    "express": "^4.18.1",
    "mongoose": "^6.3.8"
  }
}

当我像这样导入猫鼬时发生错误:

import mongoose from "mongoose";

如果我用 require 导入它没有错误

【问题讨论】:

    标签: node.js typescript mongodb mongoose


    【解决方案1】:

    此问题的解决方案是在项目基目录中找到的 tsconfig.json 文件中注释以下行,只需注释这一行。

    "esModuleInterop":true
    

    还有deprecated @types/mongoose@5.11.97: Mongoose publishes its own types, so you do not need to install this package.

    【讨论】:

    • 感谢您的回复,但是不,它不起作用,仍然存在相同的错误。有其他想法吗?
    【解决方案2】:

    Vitals 的回答对我也没有用。

    起作用的是在我的 tsconfig 中取消注释以下内容:

    "moduleResolution": "node" 
    

    希望能帮助其他人遇到这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 2022-07-26
      • 2017-03-15
      • 2023-03-30
      • 2016-10-17
      • 2019-08-16
      相关资源
      最近更新 更多