Skip to content

Commit 5a4c2a7

Browse files
authored
Merge pull request #2368 from gdg-x/firebase
Work around firebase/init.js to load config synchronous
2 parents 3664234 + bb401a9 commit 5a4c2a7

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

index.html

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,18 @@
8787

8888
// prettier-ignore
8989
{{ webVitalsPolyfill | safe }}
90+
91+
// Capture the config object from /__/firebase/init.js for src/firebase.ts
92+
window.firebase = {
93+
initializeApp: (config) => {
94+
window.firebaseConfig = config;
95+
// Delete fake Firebase global
96+
delete window.firebase;
97+
},
98+
};
9099
</script>
91100

101+
<script src="/__/firebase/init.js"></script>
92102
<script src="./src/hoverboard-app.ts" type="module"></script>
93103
<script src="./src/components/app-install.ts" type="module"></script>
94104
<script src="./src/service-worker-registration.ts" type="module"></script>

src/firebase.ts

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,31 @@
11
import { getAnalytics } from 'firebase/analytics';
2-
import { initializeApp } from 'firebase/app';
2+
import { FirebaseOptions, initializeApp } from 'firebase/app';
33
import { enableMultiTabIndexedDbPersistence, getFirestore } from 'firebase/firestore';
44
import { getPerformance, initializePerformance } from 'firebase/performance';
55

6-
const response = await fetch('/__/firebase/init.json');
7-
export const firebaseApp = initializeApp(await response.json());
6+
/**
7+
* Load Firebase config in index.html with /__/firebase/init.js. It stubs out
8+
* window.firebase.initializeApp to grab the config and saves it on the window
9+
* for use here. This is a workaround for the fact that the Firebase SDK v9 is
10+
* modular and doesn't support init.js and top-level await is not well supported
11+
* so loading from init.json caused issues with Safari, Jest, Vite, etc.
12+
*
13+
* https://github.com/gdg-x/hoverboard/pull/2368
14+
*/
15+
16+
declare global {
17+
interface Window {
18+
firebaseConfig?: FirebaseOptions;
19+
}
20+
}
21+
22+
const firebaseConfig = window.firebaseConfig;
23+
24+
if (!firebaseConfig) {
25+
throw new Error('window.firebaseConfig is not defined');
26+
}
27+
28+
export const firebaseApp = initializeApp(firebaseConfig);
829
export const db = getFirestore(firebaseApp);
930
export const performance = getPerformance(firebaseApp);
1031
export const analytics = getAnalytics(firebaseApp);

0 commit comments

Comments
 (0)