You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript配置es2022后import mongoose提示找不到模块

问题原因

当tsconfig中module配置为es2022时,TypeScript默认使用浏览器端的ES模块解析规则,不会自动查找node_modules目录下的依赖包,因此触发找不到mongoose的报错。CommonJS的require语法走Node原生模块解析逻辑,不受这个配置影响,所以不会报错。

解决方案

按顺序修改以下配置即可:

  • 第一步:补充tsconfig.json配置
    在compilerOptions中添加"moduleResolution": "node",让TS使用Node.js的模块解析规则查找依赖;同时补充ts-node的ES模块适配配置,保证ts-node-dev能正常运行ES模块代码。修改后的完整tsconfig.json如下:
    {
      "compilerOptions": {
        "target": "es2022",   
        "module": "es2022",
        "moduleResolution": "node",
        "outDir": "./build",     
        "esModuleInterop": true,   
        "forceConsistentCasingInFileNames": true,
        "strict": true,  
        "skipLibCheck": true 
      },
      "ts-node": {
        "esm": true
      }
    }
    
  • 第二步:在package.json中声明ES模块类型
    Node.js默认把.js文件识别为CommonJS模块,要运行ES模块语法(包括顶层await、import/export)的代码,需要在package.json顶层添加"type": "module"字段:
    {
      "name": "finanzas",
      "version": "1.0.0",
      "type": "module",
      "description": "API que permite gestionar las finanzas de un nucleo familiar o individuo",
      "main": "index.js",
      // 其余原有scripts、dependencies等配置保持不变
    }
    
  • (可选)清理冗余依赖
    你使用的mongoose v6版本已经内置了TypeScript类型定义,不需要额外安装@types/mongoose,旧版本的类型包反而可能引发类型冲突,可以执行命令卸载:
    npm uninstall @types/mongoose
    

改完配置后重启开发服务,报错就会消失,顶层await也可以正常使用。

内容的提问来源于stack exchange,提问作者Acuervov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 02:18:19