简体   繁体   中英

Can't import firebase-admin in Node.js

I have a Node (14.3.0) server where I enabled ES6 module imports in my package.json by adding the following line:

package.json:

"type": "module",

According to the firebase-admin docs here: https://firebase.google.com/docs/admin/setup/#node.js

If you are using ES2015, you can import the module instead:

import * as admin from 'firebase-admin';

When I use import * as admin from 'firebase-admin'; I get the following error:

credential: admin.credential.applicationDefault(),
TypeError: Cannot read property 'applicationDefault' of undefined

It seems that firebase-admin isn't imported properly - I have tried removing the "type": "module" line in package.json and importing firebase-admin with require:

const admin = require(firebase-admin)

and it works, so my question is - is it possible to import firebase-admin in Node using ES6, and if so, how?

Below is a complete, minimal, reproduction:

server.js

import express from 'express';
import * as admin from 'firebase-admin';

const app = express();
const PORT = process.env.PORT || 5000;

app.use(express.json());

admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: process.env.FIREBASE_DB_URL,
});

app.listen(PORT, () => console.log(`listening on ${PORT}`));

export default app;

package.json

{
  "name": "server",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "express": "^4.17.1",
    "firebase-admin": "^9.2.0",
  },
  "type": "module",
  "scripts": {
    "dev": "node server.js"
  },
  "engines": {
    "node": "14.x"
  }
}

NOTE: Before running the server, make sure to do in your shell (Mac/Linux):

export GOOGLE_APPLICATION_CREDENTIALS="/your/path/to/service-account-file.json"

I asked this question on the firebase-admin-node github. Apparently, they hadn't tested imports with Node 14 yet. The answer is simply:

import admin from 'firebase-admin'

You can see an explanation here:

https://github.com/firebase/firebase-admin-node/issues/1061#event-3868300300

Use it like this:

import * as admin from 'firebase-admin';
const {credential} = admin;

this way you will be able to use the functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM