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

如何根据firebase use设置的活跃项目自动切换Firebase配置

自动匹配Firebase项目与对应环境配置的方法

方案1:读取本地.firebaserc配置文件

Firebase CLI会在项目根目录生成.firebaserc文件,其中记录了当前激活的项目别名。直接读取这个文件就能判断当前环境:

const fs = require('fs');
const path = require('path');

// 读取项目根目录的.firebaserc文件
const firebaserc = JSON.parse(fs.readFileSync(path.join(__dirname, '.firebaserc'), 'utf8'));
// 获取当前默认项目的别名(即你通过firebase use设置的dev/prod)
const currentAlias = firebaserc.projects.default;

const firebaseConfigDev = {
  apiKey: "xxx",
  authDomain: "xxx-dev.firebaseapp.com",
  projectId: "xxx-dev",
  storageBucket: "xxx-dev.appspot.com",
  messagingSenderId: "12345",
  appId: "67890"
};

const firebaseConfigProd = {
  apiKey: "yyy",
  authDomain: "xxx-prod.firebaseapp.com",
  projectId: "xxx-prod",
  storageBucket: "xxx-prod.appspot.com",
  messagingSenderId: "33333",
  appId: "44444"
};

// 根据别名自动选择配置
const app = initializeApp(currentAlias === 'dev' ? firebaseConfigDev : firebaseConfigProd);

方案2:通过脚本注入环境变量

在启动或部署脚本中,先获取当前Firebase项目信息并注入为环境变量,代码中直接读取该变量即可:

  1. 修改package.json中的启动/部署脚本:
{
  "scripts": {
    "start": "export FIREBASE_CURRENT_ALIAS=$(firebase use) && node your-app.js",
    "deploy:dev": "firebase use dev && export FIREBASE_CURRENT_ALIAS=dev && firebase deploy",
    "deploy:prod": "firebase use prod && export FIREBASE_CURRENT_ALIAS=prod && firebase deploy"
  }
}
  1. 在代码中读取环境变量:
const firebaseConfigDev = {
  apiKey: "xxx",
  authDomain: "xxx-dev.firebaseapp.com",
  projectId: "xxx-dev",
  storageBucket: "xxx-dev.appspot.com",
  messagingSenderId: "12345",
  appId: "67890"
};

const firebaseConfigProd = {
  apiKey: "yyy",
  authDomain: "xxx-prod.firebaseapp.com",
  projectId: "xxx-prod",
  storageBucket: "xxx-prod.appspot.com",
  messagingSenderId: "33333",
  appId: "44444"
};

// 读取环境变量判断当前环境
const currentAlias = process.env.FIREBASE_CURRENT_ALIAS;
const app = initializeApp(currentAlias === 'dev' ? firebaseConfigDev : firebaseConfigProd);

方案3:后端场景使用Firebase Admin SDK

如果是Node.js后端应用,Firebase Admin SDK会自动读取本地Firebase CLI的配置(无需手动维护两套配置),只要你通过firebase use切换了项目,SDK就会自动匹配对应环境:

const admin = require('firebase-admin');

// 自动匹配当前Firebase CLI选中的项目配置
const app = admin.initializeApp();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:36:25