如何在React Service Worker中使用process.env [英] How to use process.env in a React service worker

查看:70
本文介绍了如何在React Service Worker中使用process.env的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置Firebase-messaging-sw.js文件(用于Web推送通知).我想知道是否有一种方法可以避免将我的Firebase配置数据尽可能向公众公开-尽管无论如何都可能将其公开?(我不太了解细微差别)

I am trying to set-up a Firebase-messaging-sw.js file (for web push notifications). I am wondering if there is a way to avoid exposing my Firebase config data to the public as much as possible - though it might be revealed anyways? (I'm not too sure about the nuances)

我尝试了以下操作:如何我可以根据环境变量自定义我的Service Worker吗?但是答案的swEnvbuild似乎没有运行,因为找不到swenv.js文件.我怀疑它可能需要在React中进行不同的设置?

I've tried following: How can I customize my Service Worker based on environment variables? But the answer's swEnvbuild doesn't seem to be running, as the swenv.js file is not found. I suspect it might need to be set-up differently in React?

(第一个问题,请随时提出对我的问题的建设性批评)

(first question, please feel free to provide constructive criticisms of my question)

推荐答案

我最近不得不使用CRA应用程序执行此操作,要查找有关它的信息并不容易,因此我认为应该分享自己的解决方案.假设您已经将 ./src/index.js 中的 serviceWorker.unregister()更改为 serviceWorker.register(),并有一个 .env 文件,其变量设置在项目的根目录中,然后您可以更新 ./src/serviceWorker.js 以包含您的 process.env 变量作为查询字符串.

I recently had to do this with a CRA app, it's not easy to find information on it so I figured I should share my solution. Assuming you've already changed serviceWorker.unregister() to serviceWorker.register() in ./src/index.js, and have a .env file with your variables set in the root of your project, then you can update ./src/serviceWorker.js to include your process.env variables as a query string.

serviceWorker.js register 函数中,如下所示更新 const swUrl ,注意 const firebaseConfig w/process.env,在 swUrl 之前声明..
./src/serviceWorker.js:

In the register function in serviceWorker.js, update const swUrl as shown below, notice the const firebaseConfig w/process.env, declared before swUrl..
./src/serviceWorker.js:

// Convert environment variables to URL `search` parameters
const firebaseConfig = new URLSearchParams({
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
  measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
}).toString();

// Service worker URL w/config variables
const swUrl = `${process.env.PUBLIC_URL}/firebase-messaging-sw.js?${firebaseConfig}`;

然后在 ./public/firebase-messaging-sw.js 中创建(如果不存在,则创建它),您可以执行以下操作..
./public/firebase-messaging-sw.js

then in ./public/firebase-messaging-sw.js (create it if it doesn't exist), you can do something like the following..
./public/firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/8.0.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.0.2/firebase-messaging.js');

// Set Firebase configuration, once available
self.addEventListener('fetch', () => {
  const urlParams = new URLSearchParams(location.search);
  self.firebaseConfig = Object.fromEntries(urlParams);
});

// "Default" Firebase configuration (prevents errors)
const defaultConfig = {
  apiKey: true,
  projectId: true,
  messagingSenderId: true,
  appId: true,
};

// Initialize Firebase app
firebase.initializeApp(self.firebaseConfig || defaultConfig);
const messaging = firebase.messaging();

// Configure message handler (assumes backend is set up)
messaging.onBackgroundMessage((payload) => {
  const { icon, body, title } = payload.data;
  self.registration.showNotification(title, { body, icon });
});    

如果有一个更理想的解决方案,很想听听它,但是这种配置对我有用.

If there's a more ideal solution, would love to hear about it, but this configuration worked for me.

这篇关于如何在React Service Worker中使用process.env的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆