2017-05-25 25 views
1

在下面的腳本,我硬編碼火力變量,我寧願不承諾回購我。我的firebase值全部在一個文件中,而我的javascript的其餘部分則使用ES6模塊(和webpack)導入這些值。但是我應該如何訪問此服務工作者文件服務工作者與非混帳致力於全局變量

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

// Initialize the Firebase app in the service worker by passing in the config.messagingSenderId. 
firebase.initializeApp({ 
    'messagingSenderId': "8033333334" 
}); 
// firebase.initializeApp({ 
// 'messagingSenderId': config.messagingSenderId 
// }); 

回答

1

數據您通過importScripts()引用的所有腳本都在同一個ServiceWorkerGlobalScope同步執行作爲主服務人員的文件。這意味着,它們共享相同的self全球性的,你知道importScripts()完成後,他們將完全執行。

所以,如果你有一個腳本調用bootstrap.js,它包含

self.config = self.config || {}; 
self.config.messagingSenderId = 'my_sender_id'; 

那麼你可以做你的service-worker.js如下:

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

firebase.initializeApp({ 
    'messagingSenderId': self.config.messagingSenderId 
}); 

這取決於你是否把在bootstrap.js檢查源代碼控制,無論你生成它在構建時飛等

+0

謝謝你,在我現有的配置文件中的'export'線引起了親blem,所以我將sw中需要的數據分隔到另一個文件中。少量重複,但絕對是一個很好的前進方向 –