Home > Enterprise >  Firebase import cannot be done outside modules
Firebase import cannot be done outside modules

Time:10-10

I'm going crazy over "writing stuff exactly what the documentation wants but came back with different outcome."

I'm trying to import firebase to my express.js API so the app can GET directly from the database.

 // Initialize Firebase
    const functions = require('firebase-functions');
    import { initializeApp } from 'firebase/app';
    
    const firebaseApp = initializeApp(firebaseConfig);
    const db = getFirestore(firebaseApp);
... //some other code

I've looked for the solution at https://firebase.google.com/docs/web/setup and SyntaxError: Cannot use import statement outside a module Firebase Functions

but seems like the problem is pretty different. The outcome still 'SyntaxError: Cannot use import statement outside a module.'

Can anyone explain what happened? Did I miss something?

CodePudding user response:

The latest Firebase version is now using the ES6/modular syntax which in return will result in SyntaxError: Cannot use import statement outside a module. You have to add the "type": "module" on your package.json. This enables ES6 modules discovery. Also, When using "module" you also have to change all your require syntax to import syntax. Here's your sample code for reference:

import * as functions from "firebase-functions";
import { initializeApp } from 'firebase/app';
    
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);

package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "type": "module",
  ...
}

For more information, you may check out this documentations:

  • Related