fix: 修复 Vercel serverless 模块路径解析问题

使用 path.resolve 动态解析 dist 目录路径,确保在 Vercel
serverless 环境中正确加载编译后的模块。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
golc 2026-03-04 11:36:02 +00:00
parent 914e156cc6
commit 43ad64dd41
1 changed files with 27 additions and 8 deletions

View File

@ -4,6 +4,7 @@ import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import express from 'express'; import express from 'express';
import bodyParser from 'body-parser'; import bodyParser from 'body-parser';
import * as path from 'path';
// 缓存 app 实例,避免每次冷启动都重新创建 // 缓存 app 实例,避免每次冷启动都重新创建
let cachedApp: any; let cachedApp: any;
@ -12,8 +13,13 @@ async function bootstrap() {
if (!cachedApp) { if (!cachedApp) {
const expressApp = express(); const expressApp = express();
// 使用 require 动态加载编译后的模块(避免 TypeScript 编译时检查) // 动态解析 dist 目录路径
const { AppModule } = require('../dist/app.module'); // 在 Vercel 环境中__dirname 是 /var/task/api
// dist 目录在 /var/task/dist
const distPath = path.resolve(__dirname, '..', 'dist', 'app.module');
console.log('Loading AppModule from:', distPath);
const { AppModule } = require(distPath);
const app = await NestFactory.create( const app = await NestFactory.create(
AppModule, AppModule,
@ -38,12 +44,25 @@ async function bootstrap() {
// 尝试加载全局过滤器和拦截器 // 尝试加载全局过滤器和拦截器
try { try {
const { const httpExceptionFilterPath = path.resolve(
HttpExceptionFilter, __dirname,
} = require('../dist/common/filters/http-exception.filter'); '..',
const { 'dist',
TransformInterceptor, 'common',
} = require('../dist/common/interceptors/transform.interceptor'); 'filters',
'http-exception.filter',
);
const transformInterceptorPath = path.resolve(
__dirname,
'..',
'dist',
'common',
'interceptors',
'transform.interceptor',
);
const { HttpExceptionFilter } = require(httpExceptionFilterPath);
const { TransformInterceptor } = require(transformInterceptorPath);
app.useGlobalFilters(new HttpExceptionFilter()); app.useGlobalFilters(new HttpExceptionFilter());
app.useGlobalInterceptors(new TransformInterceptor()); app.useGlobalInterceptors(new TransformInterceptor());
} catch (error) { } catch (error) {