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

如何在Firestore云函数中正确引入Angular(APF)库?

在Firebase云函数中引入Angular 14库的正确方式

错误核心原因:Angular 14构建的库默认输出ES模块(ESM),而Firebase云函数默认使用CommonJS(CJS)模块系统,CJS的require()无法直接加载ESM文件,因此触发ERR_REQUIRE_ESM错误。以下是三种可行解决方案:

方案一:将Firebase云函数切换为ESM模式(推荐)

适配现代ESM生态系统:

  • 修改functions/package.json,添加"type": "module"字段,声明该目录使用ESM模块系统
  • 调整functions/tsconfig.json的compilerOptions:
    {
      "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "node16",
        "target": "ES2020", // 匹配Firebase支持的Node.js版本
        "paths": {"my-lib": ["../dist/my-lib"]},
        // 保留原有其他配置
      }
    }
    
  • 保持functions/src/index.ts中的导入语句不变:import {MyClass} from "my-lib";
  • 在functions目录下执行npm install,再启动模拟器:firebase emulators:start --only functions

方案二:调整Angular库输出CommonJS格式

让Angular库同时生成CJS格式,适配云函数默认环境:

  • 打开projects/my-lib/ng-package.json,修改lib配置添加CJS格式输出:
    {
      "lib": {
        "entryFile": "src/public-api.ts",
        "format": ["esm2015", "cjs"] // 新增cjs格式
      }
    }
    
  • 重新构建Angular库:ng build my-lib,此时dist/my-lib下会生成cjs目录
  • 修改functions/tsconfig.json的paths配置,指向CJS输出目录:
    "paths": {"my-lib": ["../dist/my-lib/cjs"]}
    
  • 在functions目录下执行npm install,再启动模拟器

方案三:使用动态导入(临时应急方案)

仅适合临时测试,不推荐生产环境使用(会影响性能和类型提示):

export const helloWorld = async (req, res) => {
  // 动态加载ESM模块
  const { MyClass } = await import('my-lib');
  const myInstance = new MyClass();
  // 执行业务逻辑
  res.send('处理完成');
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:06:24