如何根据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项目信息并注入为环境变量,代码中直接读取该变量即可:
- 修改
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" } }
- 在代码中读取环境变量:
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
相关产品推荐
相关产品推荐

