有没有办法在 Angular 中添加基于 firebase 环境的配置

Is there a way to add configuration based on environment for firebase in Angular

有没有办法在Angular中添加基于firebase环境的配置?

对于开发环境和生产环境,我有不同的 firebase projectIds 和 messagingSenderIds。 我想在我的 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。 我尝试导入出现以下错误的环境。

Cannot use import statement outside a module

我也试过在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 下提到的一个或多个文件作为输入位置,并将其复制到输出位置。

然后运行测试你的service worker配置是否正确

希望这对某些人有所帮助。