Kun*_*rav 3 javascript service-worker firebase-cloud-messaging angular angular-service-worker
有没有办法在 Angular 中添加基于 firebase 环境的配置?
我有不同的 firebase projectIds 和 messagesSenderIds 用于开发环境和产品环境。我想在我正在为应用程序中的后台通知所做的 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},
);
}
}
);
Run Code Online (Sandbox Code Playgroud)
在这里,我希望根据环境使用不同的firebaseConfig。我尝试导入环境,但出现以下错误。
不能在模块外部使用 import 语句
我还尝试在 angular.json 中使用类似于环境文件的文件替换,但它也不起作用。
请帮我解决这些问题。
由于某种原因,Firebase 始终在目录的根目录中查找 firebase-messaging-sw.js 文件。因此我们无法更改该文件的名称或位置。
所以我找到了解决这个问题的方法。创建同一文件的 2 个副本并将其存储在不同的目录中。就我而言,我创建了一个名为 service-worker 的目录,并在其中创建了 2 个名为 dev 和 prod 的目录。下面是我的目录结构。
src
|---> service-worker
|----> dev
|----> prod
Run Code Online (Sandbox Code Playgroud)
然后将 firebase-messaging-sw.js 复制到 dev 和 prod 文件夹。使用环境特定配置更新了两个文件夹中的文件(硬编码)
firebase.initializeApp({
messagingSenderId: 'xxxxxxxx',
apiKey: 'xxxxxxxxxxxx',
projectId: 'xxxxxxxx',
appId: 'xxxxxxxxxxx',
});
Run Code Online (Sandbox Code Playgroud)
在 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": "/"
}
],
....
Run Code Online (Sandbox Code Playgroud)
对开发配置执行相同的操作。
它的作用是选取 glob 下提到的一个或多个文件作为输入位置,并将其复制到输出位置。
然后运行并测试您的 Service Worker 是否配置正确。
希望这对某人有所帮助。
| 归档时间: |
|
| 查看次数: |
1139 次 |
| 最近记录: |