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

在Vercel部署Express项目时自定义文件导入失败求助

Vercel部署Express项目自定义文件导入失败问题

我在Vercel上部署Express项目时,遇到自定义文件导入失败的问题——Node.js模块能正常导入,但自己写的路由文件怎么都加载不了。

项目根目录结构

.
├── app.ts
├── node_modules
├── package.json
├── package-lock.json
├── routes
└── vercel.json

2 directories, 4 files

相关代码

app.ts

import express from "express";

import testRouter from "../routes/route.js";
// Middlewares
const app = express();

app.use(testRouter);
app.get("/", (req, res) => res.send("Hello World"));

// connection
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Listening to port ${port}`));

./routes/route.js

import { Router } from "express";

const router = Router();

router.get("/test", (req, res) => {
    res.send("Hello world from test route");
});

export default router;

vercel.json

{
    "builds": [
        {
            "src": "../app.ts",
            "use": "@vercel/node"
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "app.ts"
        }
    ]
}

部署后错误

错误截图

问题分析与解决方案

1. 导入路径错误

app.ts和routes目录在同一级,导入路由时应该用相对当前文件的路径,原代码里的../routes/route.js会跳出项目根目录,导致找不到文件。

修正app.ts的导入代码:

import testRouter from "./routes/route.js";

2. Vercel配置文件路径错误

vercel.json在项目根目录,builds里的src指向../app.ts是错误的,应该直接写根目录下的app.ts。

修正vercel.json:

{
    "builds": [
        {
            "src": "app.ts",
            "use": "@vercel/node"
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "app.ts"
        }
    ]
}

3. 额外注意事项

  • 确保项目根目录有tsconfig.json,配置TypeScript编译规则,比如设置"module": "ESNext"或"CommonJS",同时开启"moduleResolution": "node"以正确解析模块路径。
  • 如果使用ES模块语法(import/export),在package.json中添加"type": "module"字段,避免解析冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:15:30