问题描述
我试图在我的 /api 文件夹中的文件中要求 bcrypt。
// pages/api/login.js
const bcrypt = require('bcrypt');
export default async function handler(req,res) {
switch (req.method) {
case 'POST':
// do stuff with bcrypt
res.status(200).json()
break
default:
res.status(405).end() //Method Not Allowed
break
}
}
当我使用 npm run dev 时一切正常,但是当我运行 npx serverless 时,我收到此错误:
ModuleNotFoundError: Module not found: Error: Can't resolve 'mock-aws-s3'
经过大量研究,这似乎发生了,因为 webpack 试图将 bcrypt 包含在客户端包中,而它应该只包含在服务器端。我不明白为什么会发生这种情况,因为根据 Next.js 文档:
Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side only bundles and won't increase your client-side bundle size.
const bcrypt = eval("require('bcrypt')");
但这感觉很hacky,就像我没有正确理解next.js。处理这种情况的正确方法是什么?为什么 webpack 试图将文件包含在 /api 中?