NextJs:Serverless 函数超出最大大小限制 50mb

Dru*_*Dog 7 deployment firebase reactjs next.js vercel

我是新使用 NextJs 的人,当尝试将我的项目部署到 Vercel 时,我收到以下错误:

错误!无服务器功能“api/auth”为 50.55mb,超出了最大大小限制 50mb。

我花了很多时间试图找到正确的答案,但没有找到。这是我发出的 api 请求的代码:

const { auth: adminAuth } = require("firebase/admin");

export default async function auth(req, res) {
  const tokenId = req.query.token;
  return new Promise((resolve) => {
    adminAuth
      .verifyIdToken(tokenId)
      .then((user) => {
        res.json(user);
        resolve();
      })
      .catch(() => {
        res.status(302).send("Invalid authentication");
        resolve();
      });
  });
}
Run Code Online (Sandbox Code Playgroud)

如果有人能帮助我,我将不胜感激,谢谢大家!

dan*_*els 2

Next.js 12.3 包含您package.json在构建中指定的依赖项以及它们的依赖项,因此可能会增加构建大小,直到达到当前的最大值 50MB。

就我而言,它是pdfjs-dist具有canvas依赖项的包。将其列为pdfjs-dist依赖项就足以package.json使 Vercel 构建失败。即使您实际上从包中导入任何文件也没关系。

Error: The Serverless Function "api/***" is 64.75mb which exceeds the maximum size limit of 50mb.
Run Code Online (Sandbox Code Playgroud)

寻找罪魁祸首

Vercel 构建日志应列出构建中包含的包及其大小。在我们的例子中:

All dependencies                                        208.68 MB         57.14 MB
Serverless Function's page: api/***
Large Dependencies                              Uncompressed size  Compressed size
node_modules/canvas/build                               164.01 MB         42.82 MB
node_modules/sharp/vendor                                16.13 MB          6.76 MB
...
Run Code Online (Sandbox Code Playgroud)

从构建中排除包

canvas在我们的例子中不需要依赖关系。要从捆绑包中排除包,从而减少无服务器函数的大小:

const nextConfig = {
  experimental: {
    outputFileTracingRoot: path.join(__dirname, '../../'),
    outputFileTracingExcludes: {
      '*': [
        'node_modules/canvas',
      ],
    },
  },
}
Run Code Online (Sandbox Code Playgroud)
  • 由于我使用的是 Next.js 12.3 和 Yarn,我最终通过使用以下内容将依赖项替换为存根package.json
  "resolutions": {
    "canvas": "https://registry.yarnpkg.com/@favware/skip-dependency/-/skip-dependency-1.2.1.tgz"
  }
Run Code Online (Sandbox Code Playgroud)

NPM 应该存在类似的解决方法。