Vercel未执行构建安装命令且无Serverless函数生成问题排查
Typescript+Express API部署Vercel失败:无构建执行/Serverless函数未生成/接口404
项目背景
我正在将基于Typescript+Express开发的API迁移至Vercel,项目的index.ts位于<root>/src目录,npm run build命令会将代码编译至<root>/dist目录。
现有代码
src/index.ts
const app = express(); app.use((req: Request, res: Response, next: NextFunction) => { // 中间件逻辑 }) app.use('/', common); // 其他路由挂载 const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Server running on ${port}, http://localhost:${port}`)); module.exports = app;
根目录vercel.json
{ "version": 2, "installCommand": "npm install", "buildCommand": "npm run build", "outputDirectory": "dist", "builds": [ { "src": "dist/index.js", "use": "@vercel/node" } ], "routes": [ { "src": "/(.*)", "dest": "dist/index.js" } ] }
当前问题
本地执行npm run build后,运行vercel dev --listen 5000可正常访问http://localhost:5000/ping并获取响应,但提交代码至Git部署后:
- 日志显示
npm install与npm run build命令未执行 - 未生成Serverless函数
/ping接口返回“Page not found”
更新后的尝试与问题
将Root Directory设置为src并勾选“Include source files outside of the Root Directory in the Build Step”后:
npm命令开始执行,但仍无Serverless函数生成/ping返回404,/路由返回index.js文件内容,本地运行也出现404- 取消勾选该选项会收到警告
Warning: The vercel.json file should exist inside the provided root directory,且仍无构建执行 - 不得不将
tsconfig.json的outDir改为"src/dist",否则会报错Error: No Output Directory named "dist" found after the Build completed. You can configure the Output Directory in your Project Settings. - 移除Root Directory后回到初始状态:无npm命令执行,但本地运行时
/路由返回“Cannot GET /”,/ping可正常响应
已参考多篇在线教程仍未解决问题,请问遗漏了哪些配置?
解决步骤
- 调整vercel.json配置,移除冗余字段
Vercel的version:2配置中,installCommand、buildCommand、outputDirectory属于平台项目设置项,放在vercel.json中易与默认逻辑冲突。正确配置应仅保留builds和routes,并直接指向源码文件:
{ "version": 2, "builds": [ { "src": "src/index.ts", "use": "@vercel/node", "config": { "includeFiles": ["dist/**"] } } ], "routes": [ { "src": "/(.*)", "dest": "/src/index.ts" } ] }
直接指定src/index.ts让Vercel自动处理编译流程,避免手动指定编译后的dist/index.js导致路径匹配失效。
- 修正Express入口文件逻辑
Vercel Node运行时无需调用app.listen(),平台会自动处理请求监听,仅在本地开发时保留该逻辑:
const app = express(); app.use((req: Request, res: Response, next: NextFunction) => { // 中间件逻辑 }) app.use('/', common); // 其他路由挂载 // 仅本地开发时启动监听 if (process.env.NODE_ENV !== 'production') { const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Server running on ${port}, http://localhost:${port}`)); } module.exports = app;
配置项目根目录与Build Settings
- 在Vercel控制台项目设置中,Root Directory留空(保持默认根目录)
- Build Command设置为
npm run build - Output Directory设置为
dist(与tsconfig.json的outDir一致) - 确保
tsconfig.json的outDir为"dist"(根目录下的dist),rootDir为"src":
{ "compilerOptions": { "rootDir": "src", "outDir": "dist", // 其他配置项 } }检查package.json的scripts
确认build命令正确触发Typescript编译:
{ "scripts": { "build": "tsc" } }
- 清理缓存重新部署
在Vercel部署页面点击Redeploy,取消勾选Use existing build cache,强制重新执行完整构建流程。
内容的提问来源于stack exchange,提问作者chibis
相关产品推荐
相关产品推荐

