backspaces
backspaces

Reputation: 3942

How can I import firebase-database as an es6 module

I want to import the firebase-database using esm import. I can only find the script version:

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

What is the url I need for the esm module version?

Note: I do not want a "bare import", I am not using webpack etc. I need a complete url.

There is an older version available on unpkg.com but not the current version.

Upvotes: 4

Views: 5439

Answers (2)

backspaces
backspaces

Reputation: 3942

It turns out there are two CDN's that can provide this: snowpack/skypack, and jspm:

skypack:

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'

These both deal with "bare import" conversion to JS, and any code conversions required to be JS Modules.

Google does not appear to want to support a module form on their firebase CDN, an Issue to that effect was immediately closed, suggesting complex workflow solutions.

I'm really thankful to the two projects above, supporting simple es6 JS and zero workflow solutions.

Edit: snowpack's esinstall can turn most js files into modules. Here's a node script that brought in all my dependencies:

#!/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()

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317692

If you're using a bundler, then follow the instructions in the 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";

For realtime database, you would add import "firebase/database".

Upvotes: 0

Related Questions