[英]Is there a way to add configuration based on environment for firebase in Angular
有沒有辦法在Angular中為firebase添加基於環境的配置?
我有不同的 firebase projectIds 和 messengingSenderIds 用於開發環境和生產環境。 我想在我正在為我的應用程序中的后台通知做的 firebase_messaging_sw.js 中使用這種不同的配置。 下面是代碼。
importScripts("https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js");
// For an optimal experience using Cloud Messaging, also add the Firebase SDK for Analytics.
importScripts("https://www.gstatic.com/firebasejs/8.2.7/firebase-analytics.js");
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
messagingSenderId: 'xxxxxxxx',
apiKey: 'xxxxxxxxxxxx',
projectId: 'xxxxxxxx',
appId: 'xxxxxxxxxxx',
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload,
);
let notificationBody;
if (payload && payload.data && payload.data.notification) {
notificationBody = JSON.parse(payload.data.notification);
}
if (notificationBody) {
return self.registration.showNotification(
notificationBody.title,
{body: notificationBody.body, icon: notificationBody.icon, image: notificationBody.image},
);
}
}
);
在這里,我希望根據環境使用不同的 firebaseConfig。 我試圖導入給出以下錯誤的環境。
不能在模塊外使用 import 語句
我還嘗試在 angular.json 中使用類似於環境文件的文件替換,但它也不起作用。
請幫我解決這些問題。
出於某種原因,Firebase 總是在目錄的根目錄中查找 firebase-messaging-sw.js 文件。 因此,我們無法更改此文件的名稱或位置。
所以我找到了解決這個問題的方法。 創建同一文件的 2 個副本並將其存儲在不同的目錄中。 就我而言,我創建了一個名為 service-worker 的目錄,並在其中創建了 2 個名為 dev 和 prod 的目錄。 下面是我的目錄結構。
src
|---> service-worker
|----> dev
|----> prod
然后將 firebase-messaging-sw.js 復制到 dev 和 prod 文件夾。 使用特定於環境的配置(硬編碼)更新了兩個文件夾上的文件
firebase.initializeApp({
messagingSenderId: 'xxxxxxxx',
apiKey: 'xxxxxxxxxxxx',
projectId: 'xxxxxxxx',
appId: 'xxxxxxxxxxx',
});
在 angular.json 添加以下更改。
configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"assets": [
"src/favicon.ico",
"src/assets",
"src/manifest.json",
{
"glob": "firebase-messaging-sw.js",
"input": "src/service-worker/prod",
"output": "/"
}
],
....
對開發配置執行相同的操作。
它的作用是選擇 glob 下提到的文件作為輸入位置,並將其復制到 output 位置。
然后運行並測試你的 service worker 是否有正確的配置。
希望這對某人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.