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

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

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

您可以使用這些方法,在應用程式中新增任何可用的程式庫

來自 CDN

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

  1. 如果只要包含特定 Firebase 產品 (例如驗證和 Cloud 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/10.12.2/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/10.12.2/firebase-analytics.js'
    
        // Add Firebase products that you want to use
        import { getAuth } from 'https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js'
        import { getFirestore } from 'https://www.gstatic.com/firebasejs/10.12.2/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@10.12.2
  2. 請使用下列任一選項,在應用程式中使用 Firebase 模組:

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

      如果只要包含特定 Firebase 產品 (例如驗證和 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 產品 (例如驗證和 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);