Utilizing environment variables in firebase-messaging-sw.js in React Boilerplate

Ume*_*shi 6 javascript reactjs service-worker firebase-cloud-messaging react-boilerplate

This is my firebase-messaging-sw.js file. What i require is to fetch environment variables from my .env file. Either directly or indirectly. I have tried other answers available here but to no avail. I am using React boilerplate and those answers just don't match up for me. Is there a way i could fetch these? Any help would be appreciated.

Code right now:

 importScripts(`https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js`)
 importScripts(`https://www.gstatic.com/firebasejs/7.17.1/firebase-messaging.js`)
    
    firebase.initializeApp({
        apiKey: `AIz.....Cvg5E_Q`,
        authDomain: `example.firebaseapp.com`,
        databaseURL: `https://example.firebaseio.com`,
        projectId: `projectid`,
        storageBucket: `example.com`,
        messagingSenderId: `1...7`,
        appId: `1..............30`,
    })
Run Code Online (Sandbox Code Playgroud)

Preferred way is to have it access from .env or some variable. By either importing or whatever. P.s Imports and require don't work in this service worker.

 importScripts(`https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js`)
 importScripts(`https://www.gstatic.com/firebasejs/7.17.1/firebase-messaging.js`)
    
    firebase.initializeApp(firebaseConfig)
Run Code Online (Sandbox Code Playgroud)

Jon*_*lez 0

我在这里提交了解决此问题的答案。总之,您需要:

  1. 创建2个.env文件
  2. 使用环境变量firebase-messaging-sw.js根文件夹中创建一个文件
  3. 安装cra-append-sw
  4. pre将脚本添加到您的package.json

查看我的另一个答案以了解实施细节。