JavaScript 模塊捆綁器可以做很多事情,但它們最有用的功能之一是能夠在您的代碼庫中添加和使用外部庫。模塊捆綁器讀取代碼中的導入路徑,並將特定於應用程序的代碼與導入的庫代碼組合(捆綁)。
從版本 9 及更高版本開始,Firebase JavaScript SDK 經過優化,可與模塊捆綁器的優化功能配合使用,以減少最終構建中包含的 Firebase 代碼量。
import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged, getRedirectResult } from 'firebase/auth';
const firebaseApp = initializeApp({ /* config */ });
const auth = getAuth(firebaseApp);
onAuthStateChanged(auth, user => { /* check status */ });
/**
* getRedirectResult is unused and should not be included in the code base.
* In addition, there are many other functions within firebase/auth that are
* not imported and therefore should not be included as well.
*/
這種從庫中刪除未使用代碼的過程稱為搖樹。手動手動刪除此代碼將非常耗時且容易出錯,但模塊捆綁器可以自動刪除此代碼。
JavaScript 生態系統中有許多高質量的模塊打包器。本指南重點介紹如何將 Firebase 與webpack 、 Rollup和esbuild 結合使用。
開始使用
本指南要求您在開發環境中安裝 npm。 npm 用於安裝和管理依賴項(庫)。要安裝 npm,請安裝自動包含 npm 的 Node.js。
大多數開發人員在安裝 Node.js 後就已正確設置。但是,許多開發人員在設置環境時會遇到一些常見問題。如果您遇到任何錯誤,請確保您的環境具有 npm CLI並且您已設置適當的權限,因此您不必以管理員身份使用 sudo 命令安裝軟件包。
package.json 和安裝 Firebase
安裝 npm 後,您需要在本地項目的根目錄下創建一個package.json
文件。使用以下 npm 命令生成此文件:
npm init
這將引導您通過嚮導來提供所需的信息。創建文件後,它將類似於以下內容:
{
"name": "your-package-name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
}
}
該文件負責許多不同的事情。如果您想了解有關模塊捆綁和一般構建 JavaScript 代碼的更多信息,這是一個重要的文件,您需要熟悉它。本指南的重要部分是"dependencies"
對象。該對象將保存您已安裝的庫及其正在使用的版本的鍵值對。
添加依賴項是通過npm install
或npm i
命令完成的。
npm i firebase
當您運行npm i firebase
時,安裝過程將更新package.json
以將 Firebase 列為依賴項:
"dependencies": {
"firebase": "^9.0.0"
},
鍵是庫的名稱,值是要使用的版本。版本值是靈活的,可以接受一系列值。這稱為語義版本控製或 semver。要了解有關 semver 的更多信息,請參閱 npm 的語義版本控制指南。
源與構建文件夾
您編寫的代碼由模塊捆綁器讀取和處理,然後作為新文件或文件集輸出。將這兩種類型的文件分開很重要。模塊捆綁器讀取和處理的代碼稱為“源”代碼。它們輸出的文件稱為構建或“dist”(分發)代碼。
代碼庫中的一個常見設置是將源代碼存儲在名為src
的文件夾中,並將構建的代碼存儲在名為dist
的文件夾中。
- src
|_ index.js
|_ animations.js
|_ datalist.js
- dist
|_ bundle.js
在上面的示例文件結構中,考慮index.js
導入了animations.js
和datalist.js
。當模塊捆綁器處理源代碼時,它將在dist
文件夾中生成bundle.js
文件。 bundle.js
是src
文件夾中的文件和導入的任何庫的組合。
如果您使用的是 Git 等源代碼控制系統,則在將此代碼存儲在主存儲庫中時,通常會忽略dist
文件夾。
入口點
模塊捆綁器都有一個入口點的概念。您可以將您的應用程序視為文件樹。一個文件從另一個文件導入代碼,依此類推。這意味著一個文件將是樹的根。此文件稱為入口點。
讓我們重溫前面的文件結構示例。
- src
|_ index.js
|_ animations.js
|_ datalist.js
- dist
|_ bundle.js
// src/index.js
import { animate } from './animations';
import { createList } from './datalist';
// This is not real code, but for example purposes only
const theList = createList('users/123/tasks');
theList.addEventListener('loaded', event => {
animate(theList);
});
src/index.js
文件被認為是入口點,因為它開始導入應用程序所需的所有代碼。模塊捆綁器使用此入口點文件開始捆綁過程。
將 Firebase 與 webpack 一起使用
Firebase 應用和 webpack 不需要特定的配置。本節介紹一般的 webpack 配置。
第一步是從 npm 安裝 webpack 作為開發依賴項。
npm i webpack webpack-cli -D
在本地項目的根目錄下創建一個名為webpack.config.js
的文件並添加以下代碼。
const path = require('path');
module.exports = {
// The entry point file described above
entry: './src/index.js',
// The location of the build folder described above
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
// Optional and for development only. This provides the ability to
// map the built code back to the original source format when debugging.
devtool: 'eval-source-map',
};
然後確保您已將 Firebase 作為依賴項安裝。
npm i firebase
然後在您的代碼庫中初始化 Firebase。以下代碼在入口點文件中導入並初始化 Firebase,並使用 Firestore Lite 加載“城市”文檔。
// src/index.js
import { initializeApp } from 'firebase/app';
import { getFirestore, doc, getDoc } from 'firebase/firestore/lite';
const firebaseApp = initializeApp({ /* config */ });
const db = getFirestore(firebaseApp);
async function loadCity(name) {
const cityDoc = doc(db, `cities/${name}`);
const snapshot = await getDoc(cityDoc);
return {
id: snapshot.id,
...snapshot.data(),
};
}
下一步是添加一個 npm 腳本來運行 webpack 構建。打開package.json
文件並將以下鍵值對添加到"scripts"
對象。
"scripts": {
"build": "webpack --mode=development"
},
要運行 webpack 並生成構建文件夾,請運行以下命令。
npm run build
最後,檢查dist
構建文件夾。它應該包含一個名為bundle.js
的文件,其中包含您的捆綁應用程序和依賴項代碼。
有關為生產優化 webpack 構建的更多信息,請參閱他們關於“模式”配置設置的官方文檔。
將 Firebase 與匯總一起使用
Firebase 應用和匯總不需要特定配置。本節介紹一般的匯總配置。
第一步是安裝 Rollup 和一個插件,用於將導入映射到使用 npm 安裝的依賴項。
npm i rollup @rollup/plugin-node-resolve -D
在本地項目的根目錄下創建一個名為rollup.config.js
的文件並添加以下代碼。
import { nodeResolve } from '@rollup/plugin-node-resolve';
export default {
// the entry point file described above
input: 'src/index.js',
// the output for the build folder described above
output: {
file: 'dist/bundle.js',
// Optional and for development only. This provides the ability to
// map the built code back to the original source format when debugging.
sourcemap: 'inline',
// Configure Rollup to convert your module code to a scoped function
// that "immediate invokes". See the Rollup documentation for more
// information: https://rollupjs.org/guide/en/#outputformat
format: 'iife'
},
// Add the plugin to map import paths to dependencies
// installed with npm
plugins: [nodeResolve()]
};
然後在您的代碼庫中初始化 Firebase。以下代碼在入口點文件中導入並初始化 Firebase,並使用 Firestore Lite 加載“城市”文檔。
// src/index.js
import { initializeApp } from 'firebase/app';
import { getFirestore, doc, getDoc } from 'firebase/firestore/lite';
const firebaseApp = initializeApp({ /* config */ });
const db = getFirestore(firebaseApp);
async function loadCity(name) {
const cityDoc = doc(db, `cities/${name}`);
const snapshot = await getDoc(cityDoc);
return {
id: snapshot.id,
...snapshot.data(),
};
}
下一步是添加一個 npm 腳本來運行匯總構建。打開package.json
文件並將以下鍵值對添加到"scripts"
對象。
"scripts": {
"build": "rollup -c rollup.config.js"
},
要運行匯總並生成構建文件夾,請運行以下命令。
npm run build
最後,檢查dist
構建文件夾。它應該包含一個名為bundle.js
的文件,其中包含您的捆綁應用程序和依賴項代碼。
有關為生產優化 Rollup 構建的更多信息,請參閱他們關於生產構建插件的官方文檔。
將 Firebase 與 esbuild 結合使用
Firebase 應用和 esbuild 不需要特定配置。本節介紹一般 esbuild 配置。
第一步是安裝 esbuild 作為開發依賴。
npm i esbuild -D
在本地項目的根目錄下創建一個名為esbuild.config.js
的文件並添加以下代碼。
require('esbuild').build({
// the entry point file described above
entryPoints: ['src/index.js'],
// the build folder location described above
outfile: 'dist/bundle.js',
bundle: true,
// Replace with the browser versions you need to target
target: ['chrome60', 'firefox60', 'safari11', 'edge20'],
// Optional and for development only. This provides the ability to
// map the built code back to the original source format when debugging.
sourcemap: 'inline',
}).catch(() => process.exit(1))
然後在您的代碼庫中初始化 Firebase。以下代碼在入口點文件中導入並初始化 Firebase,並使用 Firestore Lite 加載“城市”文檔。
// src/index.js
import { initializeApp } from 'firebase/app';
import { getFirestore, doc, getDoc } from 'firebase/firestore/lite';
const firebaseApp = initializeApp({ /* config */ });
const db = getFirestore(firebaseApp);
async function loadCity(name) {
const cityDoc = doc(db, `cities/${name}`);
const snapshot = await getDoc(cityDoc);
return {
id: snapshot.id,
...snapshot.data(),
};
}
下一步是添加一個 npm 腳本來運行 esbuild。打開package.json
文件並將以下鍵值對添加到"scripts"
對象。
"scripts": {
"build": "node ./esbuild.config.js"
},
最後,檢查dist
構建文件夾。它應該包含一個名為bundle.js
的文件,其中包含您的捆綁應用程序和依賴項代碼。
有關為生產優化 esbuild 的更多信息,請參閱他們關於縮小和其他優化的官方文檔。