Vercel部署相对导入报错:Cannot find module问题求助
解决Vercel部署时相对导入模块找不到的问题
问题重现
部署到Vercel后,API文件/api/top-tracks.ts中执行相对导入import { Card } from "../components/card";时触发报错:
2023-07-14T16:16:06.394Z undefined ERROR Error: Cannot find module '/var/task/components/card' imported from /var/task/api/top-tracks.js at new NodeError (node:internal/errors:399:5) at finalizeResolution (node:internal/modules/esm/resolve:331:11) at moduleResolve (node:internal/modules/esm/resolve:994:10) at moduleResolveWithNodePath (node:internal/modules/esm/resolve:938:12) at defaultResolve (node:internal/modules/esm/resolve:1202:79) at nextResolve (node:internal/modules/esm/loader:163:28) at ESMLoader.resolve (node:internal/modules/esm/loader:838:30) at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18) at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40) at link (node:internal/modules/esm/module_job:76:36) { code: 'ERR_MODULE_NOT_FOUND' } RequestId: 8994f047-0b25-4abb-b529-b9779fde07ce Error: Runtime exited with error: exit status 1 Runtime.ExitError
项目关键结构:
. ├── api │ ├── inf-artists.ts │ ├── inf-playing.ts │ ├── inf-tracks.ts │ ├── now-playing.ts │ └── top-tracks.ts ├── components │ ├── 404.tsx │ ├── card.tsx │ ├── cardplayer.tsx │ ├── nowplaying.tsx │ ├── readmeimg.tsx │ ├── text.tsx │ ├── track.tsx │ └── webpage.tsx
vercel.json配置:
{ "version": 2, "rewrites": [{ "source": "/(.*)", "destination": "/api/$1" }] }
解决方案
1. 补充完整文件扩展名
Node.js的ES模块(ESM)要求导入时必须指定完整文件扩展名,修改导入语句为:
import { Card } from "../components/card.tsx";
若项目经TypeScript编译后card.tsx会转为card.js,也可直接写编译后的扩展名:
import { Card } from "../components/card.js";
2. 确保components目录被纳入Serverless函数部署包
Vercel默认仅打包api目录下的文件作为Serverless函数,外部components目录可能被排除,可通过以下方式配置:
方式一:修改vercel.json添加函数配置
在配置文件中为API函数指定需要包含的文件/目录:
{ "version": 2, "rewrites": [{ "source": "/(.*)", "destination": "/api/$1" }], "functions": { "api/*.ts": { "include": ["components/**/*"] } } }
方式二:在package.json中添加files字段
通过npm的打包规则指定需要包含的文件:
{ "files": [ "api/**/*", "components/**/*" ] }
3. 检查TypeScript编译配置
确保tsconfig.json正确覆盖编译范围:
- 确认
include字段包含components目录:{ "include": ["api/**/*", "components/**/*"] } - 若配置了
outDir,需保证编译后的文件结构与源文件一致,确保API文件能找到编译后的components产物。
4. 本地预验证
先在本地执行tsc编译项目,检查编译后的api/top-tracks.js导入路径是否正确,以及components目录是否被编译到对应位置,排除本地编译问题后再重新部署。
内容的提问来源于stack exchange,提问作者Kevin Jiang
相关产品推荐
相关产品推荐

