在 next.js /api 函数处理程序中需要节点模块的正确方法是什么

问题描述

我试图在我的 /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.

我通过使用 eval 找到了解决此问题的方法

const bcrypt = eval("require('bcrypt')");

但这感觉很hacky,就像我没有正确理解next.js。处理这种情况的正确方法是什么?为什么 webpack 试图将文件包含在 /api 中?

解决方法

我之前遇到过这个问题,请确保在无服务器配置文件中同时包含 node_modules 文件夹和 package.json 文件。如果排除其中任何一个,都会抛出上述错误。

编辑: @tarandeept 这是我的包的屏幕截图:

enter image description here

这是我的文件夹结构:

enter image description here