如何在 React 服务工作者中使用 process.env [英] How to use process.env in a React service worker
问题描述
我正在尝试设置 Firebase-messaging-sw.js 文件(用于网络推送通知).我想知道是否有办法尽可能避免将我的 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 服务工作者中使用 process.env的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!