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

Vercel部署NestJs后端报错:找不到模块'src/..'求助

Vercel部署NestJS后端报错"Cannot find module 'src/..'"的解决方案

问题原因分析

  1. Vercel构建配置指向未编译TS文件:@vercel/node构建器不会自动编译NestJS的TypeScript代码,直接指定src/main.ts会导致运行时找不到模块——实际应该运行编译后dist目录下的JS文件。
  2. tsconfig路径配置错误:当前paths字段的"src": ["src/*"]无法正确解析import ... from 'src/xxx'这类导入语句,需要调整为匹配所有src子路径的格式。
  3. Vercel重写规则指向错误:rewrites的destination指向未编译的TS文件,同样会引发运行时路径解析失败。

具体修改步骤

1. 修正api目录下的package.json

确保包含正确的构建脚本,让Vercel在部署时自动编译NestJS代码:

{
  "scripts": {
    "build": "nest build",
    "start": "node dist/main.js"
  }
}

2. 修改vercel.json配置

将构建和重写规则指向编译后的dist/main.js,同时指定构建时执行编译命令:

{
  "version": 2,
  "builds": [
    {
      "src": "package.json",
      "use": "@vercel/node",
      "config": {
        "command": "npm run build"
      }
    }
  ],
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        { "key": "Access-Control-Allow-Credentials", "value": "true" },
        { "key": "Access-Control-Allow-Origin", "value": "*" },
        { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
        { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
      ]
    }
  ],
  "rewrites": [
    {
      "source": "/(.*)",
      "destination": "/dist/main.js"
    }
  ]
}

3. 修正tsconfig.json的paths配置

调整paths为正确格式,确保src/*开头的导入能被正确解析:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "paths": {
      "src/*": ["src/*"]
    }
  }
}

4. 额外注意事项

  • 不要将api目录下的node_modules提交到GitHub,Vercel会自动安装依赖。
  • 如果使用yarn,将package.json里的npm命令替换为yarn对应命令即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:53:07