在 Typescript 中定义全局 firebase 常量

Define global firebase constant in Typescript

我有一个用 Typescript 编写的服务工作线程:

export default null;
declare const self: ServiceWorkerGlobalScope;
declare const firebase: any // ### FIX THIS. This needs to be typed as firebase ####

// the imports below expose firebase global object
self.importScripts('https://www.gstatic.com/firebasejs/8.9.1/firebase-app.js');
self.importScripts(
  'https://www.gstatic.com/firebasejs/8.9.1/firebase-messaging.js'
);

self.addEventListener('install', function () {
  // do stuff here.
  firebase.initializeApp();
});

它将 firebase 定义为 any 类型的常量。我希望它与通过

获得的类型相同
import firebase from 'firebase/app';

我想 import/bundle 我的 service worker 中的 firebase,因为这会使我的 service worker 显着膨胀。导入脚本已经公开了我需要的一切(即,它们为我公开了一个全局 firebase)。

我以前也这样做过,但是 webpack 使文件从 800 字节变成了 80kb。

import firebase from 'firebase/app';

如何在不导入firebase/app附带的所有代码的情况下获取firebase的类型?

我试过这个:

export default null;
declare const self: ServiceWorkerGlobalScope;
/// <reference types="firebase/app" />
declare const firebase: firebase;

但是我收到错误 Cannot use namaespace 'firebase' as a type.

这成功了!

import type firebasetypes from 'firebase/app';
declare const firebase: typeof firebasetypes;

firebase.initializeApp({...});
firebase.messaging().onBackgroundMessage(...);