將 Firebase 添加到 JavaScript 項目的替代方法

對於大多數 Firebase Web 應用,我們強烈建議通過 npm 使用 SDK 版本 9 。但是,對於有特殊要求的用戶,Firebase 提供了添加 SDK 的替代方法。此頁面提供了這些替代方法的詳細設置說明:

  • CDN(內容分發網絡)
  • 用於 Node.js 應用程序的 npm

使用這些方法,您可以將版本 9 的任何可用庫添加到您的應用程序。

來自 CDN

您可以配置 Firebase JavaScript SDK 的部分導入並僅加載您需要的 Firebase 產品。 Firebase 將 Firebase JavaScript SDK 的每個庫存儲在我們的全球 CDN(內容分發網絡)上。

  1. 要僅包含特定的 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.22.1/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.22.1/firebase-analytics.js'
    
        // Add Firebase products that you want to use
        import { getAuth } from 'https://www.gstatic.com/firebasejs/9.22.1/firebase-auth.js'
        import { getFirestore } from 'https://www.gstatic.com/firebasejs/9.22.1/firebase-firestore.js'
      </script>
    </body>
    
  2. 添加您的 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 應用程序

  1. 安裝 Firebase JavaScript SDK:

    1. 如果您還沒有package.json文件,請通過從 JavaScript 項目的根目錄運行以下命令來創建一個:

      npm init
    2. 通過運行以下命令安裝firebase npm 包並將其保存到package.json文件中:

      npm install --save firebase@9.22.1
  2. 使用以下選項之一在您的應用中使用 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";
      
  3. 添加您的 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);