fix: 修复 Vercel serverless 模块路径解析问题
使用 path.resolve 动态解析 dist 目录路径,确保在 Vercel serverless 环境中正确加载编译后的模块。 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
914e156cc6
commit
43ad64dd41
35
api/index.ts
35
api/index.ts
|
|
@ -4,6 +4,7 @@ import { ValidationPipe } from '@nestjs/common';
|
|||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import express from 'express';
|
||||
import bodyParser from 'body-parser';
|
||||
import * as path from 'path';
|
||||
|
||||
// 缓存 app 实例,避免每次冷启动都重新创建
|
||||
let cachedApp: any;
|
||||
|
|
@ -12,8 +13,13 @@ async function bootstrap() {
|
|||
if (!cachedApp) {
|
||||
const expressApp = express();
|
||||
|
||||
// 使用 require 动态加载编译后的模块(避免 TypeScript 编译时检查)
|
||||
const { AppModule } = require('../dist/app.module');
|
||||
// 动态解析 dist 目录路径
|
||||
// 在 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(
|
||||
AppModule,
|
||||
|
|
@ -38,12 +44,25 @@ async function bootstrap() {
|
|||
|
||||
// 尝试加载全局过滤器和拦截器
|
||||
try {
|
||||
const {
|
||||
HttpExceptionFilter,
|
||||
} = require('../dist/common/filters/http-exception.filter');
|
||||
const {
|
||||
TransformInterceptor,
|
||||
} = require('../dist/common/interceptors/transform.interceptor');
|
||||
const httpExceptionFilterPath = path.resolve(
|
||||
__dirname,
|
||||
'..',
|
||||
'dist',
|
||||
'common',
|
||||
'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.useGlobalInterceptors(new TransformInterceptor());
|
||||
} catch (error) {
|
||||
|
|
|
|||
Loading…
Reference in New Issue