將 Firebase 新增至 JavaScript 專案的替代方式

對於大多數 Firebase Web 應用程式,我們強烈建議您透過 npm 使用 SDK。不過,針對有特殊需求的使用者,Firebase 提供其他新增 SDK 的方式。本頁面將說明以下替代方法的詳細設定步驟:

  • CDN (內容傳遞聯播網)
  • 適用於 Node.js 應用程式的 npm

您可以使用這些方法,將任何可用程式庫新增至應用程式。

CDN

您可以設定部分匯入 Firebase JavaScript SDK,並只載入所需的 Firebase 產品。Firebase 會將 Firebase JavaScript SDK 的每個程式庫儲存在全球 CDN (內容傳遞網路) 中。

  1. 如要只納入特定 Firebase 產品 (例如 AuthenticationCloud Firestore),請在使用任何 Firebase 服務之前,將下列指令碼新增至 <body> 標記的最下方:

    <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/11.3.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/11.3.0/firebase-analytics.js'
    
        // Add Firebase products that you want to use
        import { getAuth } from 'https://www.gstatic.com/firebasejs/11.3.0/firebase-auth.js'
        import { getFirestore } from 'https://www.gstatic.com/firebasejs/11.3.0/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@11.3.0
  2. 請使用下列其中一種方式,在應用程式中使用 Firebase 模組:

    • 您可以從任何 JavaScript 檔案require模組

      如要只納入特定 Firebase 產品 (例如 AuthenticationCloud 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 產品 (例如 AuthenticationCloud 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);