You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase App Hosting部署Next.js时触发Functions错误,原因何在?

问题解决:Firebase App Hosting Rollout失败,报错找不到firebase-functions/v2模块

问题背景

使用Next.js部署Firebase App Hosting的Create Rollout操作失败,报错:

Type error: Cannot find module 'firebase-functions/v2/scheduler' or its corresponding type declarations.

复现场景下的错误:

Failed to compile.
./functions/src/index.ts:10:25 Type error: Cannot find module 'firebase-functions/v2/https' or its corresponding type declarations.
10 | import {onRequest} from "firebase-functions/v2/https";

已确认信息:

  • 单独执行firebase deploy部署Functions成功,函数可正常运行
  • Functions目录下的package.json已配置"firebase-functions": "^6.1.0"(支持v2版本)
  • 疑问:Firebase App Hosting与Functions应为独立部署目标,为何构建App时会触发Functions的模块错误

原因分析

Firebase App Hosting构建Next.js应用时,会沿用Next.js默认的构建逻辑——扫描项目根目录下所有TypeScript/JavaScript文件(包括functions/子目录)。但App Hosting的构建环境并未安装Functions目录下的依赖(仅部署Functions时才会安装该目录的依赖),因此当Next.js尝试解析Functions代码中的firebase-functions/v2导入时,会因找不到模块而报错。

解决方案

方案1:修改Next.js配置,忽略Functions目录

在项目根目录的next.config.js中添加webpack配置,让Next.js构建时跳过functions目录:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    // 排除functions目录下的TS/TSX文件
    config.module.rules.forEach(rule => {
      if (rule.test.toString().includes('tsx|ts')) {
        rule.exclude = [...(rule.exclude || []), /functions/];
      }
    });
    return config;
  },
};

module.exports = nextConfig;

方案2:将Functions目录移出项目根目录

把functions/文件夹移动到项目外部,这样Next.js构建时不会扫描到该目录。部署Functions时,通过指定目录的方式执行命令:

firebase deploy --only functions --project your-project-id --functions-dir ../functions

方案3:根目录安装firebase-functions依赖(不推荐)

在项目根目录的package.json中添加firebase-functions依赖:

npm install firebase-functions@^6.1.0

此方案会增加App Hosting的构建体积,且无实际必要,仅作为临时应急方案。

内容的提问来源于stack exchange,提问作者esafresa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:46:19