我正在使用 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 管理员似乎支持 TypeScript。 有人可以告诉我们如何在云功能上使用 typescript 和 firebase-admin 吗?
https://firebase.google.com/support/release-notes/admin/node#4.1.3
您不需要安装
@types
模块,因为 firebase-admin
附带了 TypeScript 支持。只需安装 firebase-admin
,您就应该能够将它与 TypeScript 一起使用。
import * as admin from 'firebase-admin';
另一种选择可能是这样的。
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)
});
使用 ES6 模块导入时似乎提供了类型:
tsconfig.json
{
"compilerOptions": {
"resolveJsonModule": true, // json imports
"esModuleInterop": true, // import common modules as ES6 Modules
"allowSyntheticDefaultImports": true, // support typesystem compatibility
}
}
index.ts
import firebase from 'firebase-admin';
import serviceAccount from './service-account.json';
//snake_case to camelCase
const params = {
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),
})
对于那些仍在苦苦挣扎的人,安装 firebase-admin 后重新加载 VSCode 为我完成了工作。
我知道我迟到了,但我找到了另一种方法来做到这一点,使用彼得给出的答案:
{
"compilerOptions": {
"resolveJsonModule": true, // json imports
"esModuleInterop": true, // import common modules as ES6 Modules
"allowSyntheticDefaultImports": true, // support typesystem compatibility
}
}
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.
})
import { initializeApp, cert } from 'firebase-admin/app';
import { getMessaging } from 'firebase-admin/messaging';
const app: App = initializeApp(
{
credential: cert('./firebase.json'),
},
'appname',
);
class PushNotificationService {
options = {
priority: 'high',
timeToLive: 60 * 60 * 24,
};
send = (userToken: any, message: any): void => {
getMessaging(app)
.sendToDevice(userToken, message, this.options)
.then(response => {
console.log('Successfully sent message:', response);
})
.catch(error => {
console.log('Error sending message:', error);
});
};
}
export default PushNotificationService;
import * as admin from 'firebase-admin';
const serviceAccount = require('./firebase.json');
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
export const firebaseDB = admin.firestore();