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

无法在Firebase Functions中使用i18n-js,求解决思路

解决Firebase Functions中i18n-js使用时的SyntaxError: Unexpected token 'export'问题

问题原因

你的代码混用了CommonJS模块语法(require/exports)和ES模块语法(import/export),Node.js在未正确配置的情况下无法兼容两种模块系统,导致解析时出现语法错误。

解决方案

统一使用ES模块语法(符合现代TypeScript项目规范),并修正代码中的小错误:

1. 重构i18n.ts为ES模块

将原来的require和exports替换为ES模块的import和export:

// src/i18n.ts
import i18n from 'i18n-js';

i18n.locale = 'en';
i18n.fallbacks = true;
i18n.translations = {
  en: { hello: 'Hello' },
  es: { hello: 'Hola' },
  fr: { hello: 'Bonjour' },
};

export default i18n;

2. 修正testFunction.ts的导入和变量引用

把i18n的require改为ES模块导入,同时修正dummyVar的引用(原代码直接写dummyVar会导致未定义错误):

// src/testFunction/testFunction.ts
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import i18n from '../i18n';

admin.initializeApp();

const testFunction = functions.https.onCall(
  async (data: { dummyVar: string }, context) => {
    // 修正:通过data.dummyVar访问传入的变量
    console.log(i18n.t('hello'), data.dummyVar);
  }
);

export default testFunction;

3. 确保TypeScript配置正确

检查tsconfig.json,确保模块相关配置支持ES模块:

{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ES2020",
    "moduleResolution": "NodeNext",
    "esModuleInterop": true,
    "outDir": "./lib",
    "rootDir": "./src",
    "strict": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

4. 验证Firebase部署配置

确保firebase.json中functions的source指向编译后的输出目录(通常是lib):

{
  "functions": {
    "source": "lib"
  }
}

完成以上步骤后,重新编译并部署Firebase Functions即可解决错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 06:12:10