如何将 firebase-database 作为 es6 模块导入

How can I import firebase-database as an es6 module

我想使用 esm import 导入 firebase 数据库。我只能找到脚本版本:

<script src="https://www.gstatic.com/firebasejs/7.21.0/firebase-database.js"></script>

我需要什么 url esm 模块版本?

注意:我不想要“裸导入”,我没有使用 webpack 等。我需要一个完整的 url。

unpkg.com 上有旧版本可用,但当前版本不可用。

如果您使用的是捆绑器,请按照 documentation 中的说明进行操作:

Install the firebase npm package and save it to your package.json file by running:

npm install --save firebase

To include only specific Firebase products (like Authentication and Cloud Firestore), import Firebase modules:

// Firebase App (the core Firebase SDK) is always required and must be listed first
import * as firebase from "firebase/app";

// If you enabled Analytics in your project, add the Firebase SDK for Analytics
import "firebase/analytics";

// Add the Firebase products that you want to use
import "firebase/auth";
import "firebase/firestore";

对于实时数据库,您将添加 import "firebase/database"

事实证明有两个 CDN 可以提供此功能:snowpack/skypack 和 jspm:

天空包:

import firebase from 'https://cdn.skypack.dev/@firebase/app'
import 'https://cdn.skypack.dev/@firebase/database'

jspm:

import { firebase } from 'https://jspm.dev/@firebase/app'
import 'https://jspm.dev/@firebase/database'

这些都处理到 JS 的“裸导入”转换,以及任何需要成为 JS 模块的代码转换。

Google 似乎不想在他们的 firebase CDN 上支持模块形式,一个与此相关的问题立即关闭,建议使用复杂的工作流解决方案。

非常感谢上面两个项目,支持简单的es6 JS和零工作流方案

编辑:snowpack 的 esinstall 可以将大多数 js 文件转换为模块。这是一个引入了我所有依赖项的节点脚本:

#!/usr/bin/env node --require esm
import { install } from 'esinstall'
import nodePolyfills from 'rollup-plugin-node-polyfills'
async function run() {
    const foo = await install(
        [
            'mapbox-gl',
            'three',
            'three/examples/jsm/controls/OrbitControls.js',
            'three/src/core/Object3D.js',
            'chart.js',
            'dat.gui',
            'fflate',
            '@turf/turf',
            'stats.js',
            '@firebase/app',
            '@firebase/database',
        ],
        {
            rollup: {
                plugins: [nodePolyfills()],
            },
        }
    )
}
run()