TL;DR-为什么导入返回undefined
?特别是对于像path
这样的本地节点模块
我有一个非常小的测试应用程序,它是用Vite构建的,在/api
目录中有一个端点。我创建这个只是为了玩Vite+Vercel。
我的端点只有两个模块导入-path
和fs-extra
。两者都以undefined
的形式返回。我在path
模块中得到了cannot read join of undefined
错误,所以我将所有内容都封装在try/catch
中,只是为了查看端点是否响应。确实如此。请参阅下面的代码。
import type {VercelRequest, VercelResponse} from '@vercel/node'
import path from 'node:path' // I've also tried 'path'
import fs from 'fs-extra'
export default function handler(req: VercelRequest, res: VercelResponse) {
// Both of these log 'undefined' on my Vercel dashboard for function logs.
console.log('path module:', path)
console.log('fs module:', fs)
try {
// https://vercel.com/guides/how-can-i-use-files-in-serverless-functions
const pathFromProjectRootToFile = '/api/usersData.json'
const usersDataFilePath = path.join( // THIS IS WHERE THE ERROR HAPPENS 🙃
process.cwd(),
pathFromProjectRootToFile
)
const usersData = fs.readJSONSync(usersDataFilePath)
res.json({users: usersData})
} catch (e) {
res.json({error: errorToObject(e as Error)})
}
}
function errorToObject(err?: Error): Record<string, string> | null {
if (!err || !(err instanceof Error)) return null
const obj: Record<string, string> = {}
Object.getOwnPropertyNames(err).forEach(prop => {
const value = err[prop as keyof Error]
if (typeof value !== 'string') return
obj[prop] = value
})
return obj
}
顺便说一句,我也只尝试了path
,而不是node:path
,但还是一样——undefined
。我的package.json
中确实有fs-extra
作为依赖项。
在Vercel上部署Vite应用程序并将/api
目录用于具有无服务器功能的后端时,节点模块需要通过require
而不是import
导入。import
语法适用于类型和本地模块。请参阅Vercel社区讨论中的答案(和对话(。
import type {VercelRequest, VercelResponse} from '@vercel/node'
import localModule from '../myLocalModule'
const path = require('path')
const fsOriginal = require('fs')
const fs = require('fs-extra')
// Rest of the file here...