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

對於大多數 Firebase 網頁應用程式,我們強烈建議透過 npm 使用 SDK。不過,如果使用者有特殊需求,Firebase 也提供其他新增 SDK 的方式。本頁提供這些替代方法的詳細設定操作說明:

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

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

從 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/13.2.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/13.2.0/firebase-analytics.js'
    
        // Add Firebase products that you want to use
        import { getAuth } from 'https://www.gstatic.com/firebasejs/13.2.0/firebase-auth.js'
        import { getFirestore } from 'https://www.gstatic.com/firebasejs/13.2.0/firebase-firestore.js'
      </script>
    </body>
  2. 新增 Firebase 設定物件,然後在應用程式中初始化 Firebase:

    <body>
      <script type="module">
        // ...
    
        // TODO: Replace the following with your app's Firebase 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@13.2.0
  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");
      


    • 您可以使用 ESM 語法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 configuration
    const firebaseConfig = {
      //...
    };
    
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);