简体   繁体   中英

Cannot find module 'mongoose' with typeScript

I want to use await in a top-level function, and to do that typeScript requests me to put my target language in the tsconfig.json to 2017 or higher and the module to es2022. But when I do that, there is this error: "Cannot find module 'mongoose'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?"

I have already searched in a lot of places but I did not find a solution for that.

Here is some of my code:

The tsconfig.json

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

package.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"
  }
}

And the error occurs when I import mongoose like this:

import mongoose from "mongoose";

if I imported it with require there is no error

The solution to this problem is to comment the below line in your tsconfig.json file found in your project's base directory, just comment this line.

"esModuleInterop":true

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

Vitals's answer didn't work for me either.

What did work was uncommenting the following in my tsconfig:

"moduleResolution": "node" 

Hope that helps anyone else running into this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM