对于大多数 Firebase Web 应用,我们强烈建议通过 npm 使用 SDK 版本 9 。但是,对于有特殊要求的用户,Firebase 提供了添加 SDK 的替代方法。此页面提供了这些替代方法的详细设置说明:
- CDN(内容分发网络)
- 用于 Node.js 应用程序的 npm
使用这些方法,您可以将版本 9 的任何可用库添加到您的应用程序。
来自 CDN
您可以配置 Firebase JavaScript SDK 的部分导入并仅加载您需要的 Firebase 产品。 Firebase 将 Firebase JavaScript SDK 的每个库存储在我们的全球 CDN(内容分发网络)上。
要仅包含特定的 Firebase 产品(例如 Authentication 和 Cloud Firestore),请将以下脚本添加到
<body>
标记的底部,但在您使用任何 Firebase 服务之前:<body> <!-- Insert this script at the bottom of the HTML, but before you use any Firebase services --> <script type="module"> import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js' // If you enabled Analytics in your project, add the Firebase SDK for Google Analytics import { getAnalytics } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js' // Add Firebase products that you want to use import { getAuth } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js' import { getFirestore } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js' </script> </body>
添加您的 Firebase 配置对象,然后在您的应用中初始化 Firebase:
<body> <script type="module"> // ... // TODO: Replace the following with your app's Firebase project configuration const firebaseConfig = { // ... }; // Initialize Firebase const app = initializeApp(firebaseConfig); </script> </body>
Node.js 应用程序
安装 Firebase JavaScript SDK:
如果您还没有
package.json
文件,请通过从 JavaScript 项目的根目录运行以下命令来创建一个:npm init
通过运行以下命令安装
firebase
npm 包并将其保存到package.json
文件中:npm install --save firebase@9.15.0
使用以下选项之一在您的应用中使用 Firebase 模块:
你可以从任何 JavaScript 文件中
require
模块要仅包含特定的 Firebase 产品(例如 Authentication 和 Cloud Firestore):
// Firebase App (the core Firebase SDK) is always required and // must be listed before other Firebase SDKs var firebase = require("firebase/app"); // Add the Firebase products that you want to use require("firebase/auth"); require("firebase/firestore");
可以使用 ES2015
import
模块要仅包含特定的 Firebase 产品(例如 Authentication 和 Cloud Firestore):
// Firebase App (the core Firebase SDK) is always required and // must be listed before other Firebase SDKs import firebase from "firebase/app"; // Add the Firebase services that you want to use import "firebase/auth"; import "firebase/firestore";
添加您的 Firebase 配置对象,然后在您的应用中初始化 Firebase:
import { initializeApp } from 'firebase/app'; // TODO: Replace the following with your app's Firebase project configuration const firebaseConfig = { //... }; // Initialize Firebase const app = initializeApp(firebaseConfig);