firebase-admin在firebase云功能中使用typescript

时间:2017-05-27 18:28:28

标签: typescript firebase google-cloud-functions firebase-admin

我在云功能上使用firebase云功能和javascript。 而且,我想从javascript切换到打字稿。

但是我不能在typescript上使用firebase-admin,因为以下命令失败。

command: npm install @types/firebase-admin --save-dev
error:  '@types/firebase-admin' is not in the npm registry.

根据此发行说明,它看起来firebase管理员支持打字稿。 有人可以告诉我们如何在云功能上使用带有firebase-admin的typescript吗?

https://firebase.google.com/support/release-notes/admin/node#4.1.3

5 个答案:

答案 0 :(得分:6)

您无需安装@types模块,因为firebase-admin附带了TypeScript支持。您只需安装firebase-admin即可将其与TypeScript一起使用。

答案 1 :(得分:1)

使用ES6模块导入时似乎提供了类型:

  1. tsconfig.json
{
    "compilerOptions": {
        "resolveJsonModule": true,               // json imports
        "esModuleInterop": true,                 // import common modules as ES6 Modules
        "allowSyntheticDefaultImports": true,    // support typesystem compatibility
    }
}
  1. index.ts
import firebase from 'firebase-admin';
import serviceAccount from './service-account.json';

const params = {               //clone json object into new object to make typescript happy
    type: serviceAccount.type,
    projectId: serviceAccount.project_id,
    privateKeyId: serviceAccount.private_key_id,
    privateKey: serviceAccount.private_key,
    clientEmail: serviceAccount.client_email,
    clientId: serviceAccount.client_id,
    authUri: serviceAccount.auth_uri,
    tokenUri: serviceAccount.token_uri,
    authProviderX509CertUrl: serviceAccount.auth_provider_x509_cert_url,
    clientC509CertUrl: serviceAccount.client_x509_cert_url
}

firebase.initializeApp({
    credential: firebase.credential.cert(params),
})

答案 2 :(得分:0)

我知道我迟到了,但我找到了另一种方法来做到这一点,使用彼得给出的答案:

  1. tsconfig.json
{
    "compilerOptions": {
        "resolveJsonModule": true,               // json imports
        "esModuleInterop": true,                 // import common modules as ES6 Modules
        "allowSyntheticDefaultImports": true,    // support typesystem compatibility
    }
}
  1. index.ts
import firebase from 'firebase-admin';
import serviceAccount from './service-account.json';

firebase.initializeApp({
    credential: firebase.credential.cert(serviceAccount as any), //Cast as any instead of clone the JSON.
})

答案 3 :(得分:0)

另一种选择可能是这种方式。

import * as admin from 'firebase-admin';
import * as serviceAccount from './service-account.json';

const firebaseAdmin = admin.initializeApp({
   credential: admin.credential.cert(serviceAccount as admin.ServiceAccount)
});

答案 4 :(得分:-1)

对于那些仍在苦苦挣扎的人,在安装 firebase-admin 后重新加载 VSCode 对我有用。