Source:  Twitter logo

I am attempting to set up my sveltekit project so my firebase SDK points to emulators in my local environment, and the actual database in the real environment. By default, the firebase functions point to prod, and I want to tell it to use the emulators ONLY in a dev environment.

The following firebase initialization does the trick:

// initFirebase.ts

import { initializeApp } from 'firebase/app';
import { firebaseConfig } from './env';
import { getFirestore, connectFirestoreEmulator } from 'firebase/firestore';
import { getAuth, connectAuthEmulator } from 'firebase/auth';

const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth();

if (import.meta.env.MODE === 'development') {
    connectAuthEmulator(auth, 'http://localhost:9099');
    connectFirestoreEmulator(db, 'localhost', 8080);
}

...but when I run this in Cypress, the browser throws the following error after starting my tests:

Error: Webpack Compilation Error
./src/initFirebase.ts 8:10
Module parse failed: Unexpected token (8:10)
File was processed with these loaders:
 * ../../.cache/Cypress/8.7.0/Cypress/resources/app/packages/server/node_modules/ts-loader/index.js
You may need an additional loader to handle the result of these loaders.
| export const db = getFirestore(app);
| export const auth = getAuth();
> if (import.meta.env.MODE === 'development') {
|     connectAuthEmulator(auth, 'http://localhost:9099');

This error is only thrown when opening in Cypress. The application works fine when opening it in a standalone browser. It looks like this is an issue with Cypress not recognizing the Vite environment variables (import.meta.env.MODE).

Workaround

I've resorted to leaving the emulator functions in by default while developing (without the if conditional), then I comment them out when I deploy to prod. I'd prefer a programmatic way to make this happen.

Questions

  • Is there a way to get Cypress to recognize Vite environment variables?
  • Is there any other way to split this logic so the emulator URLs are used in Cypress, but not in prod?

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).