From f557f8581b4223bb7c99ff71a4d747c1f5d21c0d Mon Sep 17 00:00:00 2001 From: golc <2483469113@qq.com> Date: Wed, 4 Mar 2026 11:14:09 +0000 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20Vercel=20serverless?= =?UTF-8?q?=20=E8=BF=90=E8=A1=8C=E6=97=B6=E5=B4=A9=E6=BA=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 关键修复: - 使用 require() 而非 import() 动态加载编译后的模块 - 从 dist/src/ 路径加载模块(Vercel 构建后的路径) - 移除 tsconfig 中对 api 目录的排除 - 配置 vercel.json 路由到 dist/api/index.js 技术说明: - api/index.ts 会被编译到 dist/api/index.js - 运行时从 dist/src/app.module 加载 NestJS 应用 - 使用 require 避免 TypeScript 编译时路径检查 Co-Authored-By: Claude Sonnet 4.6 --- api/index.ts | 10 +++++----- tsconfig.json | 2 +- vercel.json | 14 +++++++++++++- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/api/index.ts b/api/index.ts index 73898cd..5369dd6 100644 --- a/api/index.ts +++ b/api/index.ts @@ -5,9 +5,6 @@ import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import express from 'express'; import bodyParser from 'body-parser'; -// 从源码导入,TypeScript 会编译到 dist -import { AppModule } from '../src/app.module'; - // 缓存 app 实例,避免每次冷启动都重新创建 let cachedApp: any; @@ -15,6 +12,9 @@ async function bootstrap() { if (!cachedApp) { const expressApp = express(); + // 使用 require 动态加载编译后的模块(避免 TypeScript 编译时检查) + const { AppModule } = require('../dist/src/app.module'); + const app = await NestFactory.create( AppModule, new ExpressAdapter(expressApp), @@ -38,8 +38,8 @@ async function bootstrap() { // 尝试加载全局过滤器和拦截器 try { - const { HttpExceptionFilter } = await import('../src/common/filters/http-exception.filter'); - const { TransformInterceptor } = await import('../src/common/interceptors/transform.interceptor'); + const { HttpExceptionFilter } = require('../dist/src/common/filters/http-exception.filter'); + const { TransformInterceptor } = require('../dist/src/common/interceptors/transform.interceptor'); app.useGlobalFilters(new HttpExceptionFilter()); app.useGlobalInterceptors(new TransformInterceptor()); } catch (error) { diff --git a/tsconfig.json b/tsconfig.json index bf23ec1..faf5591 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,5 +18,5 @@ "forceConsistentCasingInFileNames": false, "noFallthroughCasesInSwitch": false }, - "exclude": ["node_modules", "dist", "api"] + "exclude": ["node_modules", "dist"] } diff --git a/vercel.json b/vercel.json index 85deee8..c41475d 100644 --- a/vercel.json +++ b/vercel.json @@ -1,3 +1,15 @@ { - "version": 2 + "version": 2, + "builds": [ + { + "src": "package.json", + "use": "@vercel/node" + } + ], + "routes": [ + { + "src": "/(.*)", + "dest": "/dist/api/index.js" + } + ] }