過去,在我的 Angular 專案中初始化 Firebase App 和 App Check,以及擷取 Remote Config 參數之前,我總是重複進行以下工作。
步驟:
public/,以便能包含在正式環境建置的 dist/ 資料夾中。public/ 中建立 firebase.config.json 檔案,以儲存 Firebase API Key、reCAPTCHA 金鑰以及其他設定。firebase.config.json 加入 .gitignore,這樣它就不會被意外提交到遠端存放庫。雖然 API 金鑰和 reCAPTCHA 金鑰是公開的,但 GitHub 總是會向我發送關於密鑰外洩的警示電子郵件。為了省去麻煩,我將該檔案加入 git ignore。ConfigService 來執行初始化邏輯。步驟 1 到 4 都是手動工作,我最終使用 antigravity CLI 和 Gemini 透過三個 Node.js 指令碼實現了自動化。
以下我將展示如何提示 Gemini 產生這些指令碼:
讓我向您展示這是如何完成的。
npm i --save-exact firebase
npm i --save-exact --save-dev firebase-tools
firebase 是負責初始化 Firebase App 並建置 AI 功能的 Firebase JavaScript SDK。我預先安裝了這個相依套件。另一方面,firebase-tools 則是負責執行 Firebase CLI 指令的開發相依套件。
這是第一個提示詞:
/grill-me-docs I would like to have a Node.JS script to fetch the default values of Firebase Remote Config. The project is the default project, the script must be written in ESM format, and save as firebase/get-firebase-remote-config.mjs. Pleas write the output to public/remote-config-defaults.json.
Gemini 回覆表示透過 Firebase CLI 呼叫 Remote Config 的 Get API 是可行的。它起草了一個計畫,我迅速批准並繼續進行。
當我在 Firebase UI 中點擊 Download default values 按鈕時,它下載了一個包含鍵值組的 JSON 物件。因此,我以為該指令碼會回傳相同的格式給我,但事實並非如此。
Gemini 產生了指令碼,我決定手動進行測試。我在 package.json 中新增了一個指令碼來呼叫該 mjs 檔案:
"scripts": {
... other scripts....,
"config:fetch": "node firebase/scripts/get-firebase-remote-config.mjs"
}
當我執行 npm run config:fetch 時,遇到了兩個問題。
我的提示詞沒有提到我會在哪裡呼叫該指令碼,因此 JSON 檔案沒有被寫入 <project>/public/remote-config-defaults.json。
該檔案是有效的 JSON,但內容並不是我想要的鍵值組。因此,我向 Gemini 解釋了這些問題以進行修正。
提示詞類似於:
I added a config:fetch script to call firebase/scripts/get-firebase-remote-config.mjs in package.json. When I executed npm run config:fetch in the terminal, the file was not in <project>/public/. Moreover, the content of the JSON file should be key/value pairs. Please fix both issues for me.
Gemini 分析了提示詞並代表我修正了指令碼。當我再次執行 npm run config:fetch 時,JSON 檔案出現在預期的位置,且格式正確無誤。
{
... other parameters ...
"geminiModelName": "gemini-3.8-flash",
"useLimitedUseAppCheckTokens": "true",
"vertexAILocation": "global"
}
Angular 應用程式可以輕鬆匯入該 JSON 檔案,並將該物件指派給 Firebase Remote Config 的預設設定。
我想要一個 Node.js 指令碼來建構包含 Firebase 設定、reCAPTCHA 金鑰和 App Check 偵錯權杖(Debug Token)的 JSON 物件。接著,我可以匯入該 JSON 檔案並使用這些數值來初始化 Firebase 應用程式和 App Check。
{
"app": {
"apiKey": "",
"authDomain": "",
"projectId": "",
"storageBucket": "",
"messagingSenderId": "",
"appId": ""
},
"recaptchaEnterpriseKey": "",
"appCheckDebugToken": ""
}
Firebase CLI 是一個非常強大的工具,但我不確定 CLI 是否有指令可以擷取這些數值。
我提示了 Gemini 以取得一些見解:
/grill-me-docs Can I use Firebase CLI to retrieve the value of Firebase API Key, authDomain, reCAPTCHA Key, and App Check Debug Token? I would like to have a Node.js script to generate a JSON object in this format,
{
"app": {
"apiKey": "",
"authDomain": "",
"projectId": "",
"storageBucket": "",
"messagingSenderId": "",
"appId": ""
},
"recaptchaEnterpriseKey": "",
"appCheckDebugToken": ""
}
Gemini 回覆表示 Firebase CLI 無法擷取 reCAPTCHA 金鑰和 App Check Debug Token,替代方案是將這兩個數值儲存在 .env 檔案中。
另一方面,Firebase CLI 可以依專案 ID 和應用程式 ID 擷取 Firebase 設定物件。我比較傾向依預設專案 ID 和應用程式名稱進行查詢。經過漫長的討論後,制定出了一項計畫。
注意: 預設專案 ID 是 .firebaserc 檔案中的 default。
{
"projects": {
"default": "<default project ID>"
}
}
.env.example 和 .env 中。firebase/generate-firebase-config.mjs 來建構 Firebase 設定物件
.env 檔案載入數值{ app: {...}, recaptchaEnterpriseKey, appCheckDebugToken }
public/firebase.config.json
firebase.config.json 加入 .gitignore 以忽略該檔案APP_FIREBASE_WEB_APP_NAME="<Firebase Web App Display Name>"
APP_FIREBASE_RECAPTCHA_ENTERPRISE_KEY="<Recaptcha Enterprise Key>"
APP_FIREBASE_APPCHECK_DEBUG_TOKEN="<App Check debug token>"
環境變數檔案只有三個環境變數。
最終的指令碼非常長,我擷取了重要部分在此展示:
async function fetchSdkConfigViaCli(webAppName) {
const { stdout: listStdout } = await execAsync('npx firebase apps:list WEB --json --project default', {
cwd: firebaseDir,
});
const listResponse = JSON.parse(listStdout);
const apps = listResponse?.result || [];
const targetApp = apps.find((app) => app.displayName === webAppName);
const { appId } = targetApp;
const { stdout: sdkStdout } = await execAsync(`npx firebase apps:sdkconfig WEB ${appId} --json --project default`, {
cwd: firebaseDir,
});
const sdkResponse = JSON.parse(sdkStdout);
const sdkConfig = sdkResponse?.result?.sdkConfig;
return {
apiKey: sdkConfig.apiKey,
authDomain: sdkConfig.authDomain,
projectId: sdkConfig.projectId,
storageBucket: sdkConfig.storageBucket,
messagingSenderId: sdkConfig.messagingSenderId,
appId: sdkConfig.appId,
};
}
process.loadEnvFile();
const app = fetchSdkConfigViaCli(process.env.APP_FIREBASE_WEB_APP_NAME)
const config = {
app,
recaptchaEnterpriseKey: process.env.APP_FIREBASE_RECAPTCHA_ENTERPRISE_KEY,
appCheckDebugToken: process.env.APP_FIREBASE_APPCHECK_DEBUG_TOKEN,
};
fs.writeFileSync(outputPath, `${JSON.stringify(config, null, 2)}\n`, 'utf-8');
該指令碼載入 .env,並使用 Web 應用程式名稱取得 SDK 設定。接著,它將 SDK 設定、reCAPTCHA 金鑰和 App Check Debug Token 合併到 config 物件中。最後,將 config 物件寫入 public/firebase.config.json。
將 firebase.config.json 加入 .gitignore 檔案,這樣它就不會被推送到 GitHub 存放庫。
# generated firebase configuration
firebase.config.json
"scripts": {
... other scripts ...
"config:generate": "node firebase/scripts/generate-firebase-config.mjs"
}
執行 npm run config:generate 並驗證結果是否正確。
上述指令碼在開發和正式環境部署中都非常實用。當應用程式部署到 Firebase App Hosting 時,正式環境建置應該使用最新的數值。因此,我提示 Gemini 產生一個新的 prebuild.mjs Node.js 指令碼來同時執行這兩個指令碼。
try {
await Promise.all([import('./get-firebase-remote-config.mjs'), import('./generate-firebase-config.mjs')]);
} catch (error) {
process.exit(1);
}
建置前指令碼以平行方式執行這兩者,因為它們是互相獨立的操作。
更新 package.json 以新增 prebuild 指令碼:
"scripts": {
... other scripts ...
"prebuild": "node firebase/scripts/prebuild.mjs"
}
當使用者在終端機中執行 npm run build 時,建置前指令碼會覆寫 Remote Config 預設值以及 Firebase 設定物件。
今天就到這裡。我們建立了三個 Node.js 指令碼來簡化應用程式初始化、安全性和 Remote Config 的啟用。