JavaScript 模組捆綁器可以做很多事情,但它們最有用的功能之一是能夠在程式碼庫中新增和使用外部程式庫。模組捆綁器讀取程式碼中的導入路徑,並將特定於應用程式的程式碼與導入的庫程式碼組合(捆綁)。
從版本 9 及更高版本開始,Firebase JavaScript 模組化 API 經過最佳化,可與模組捆綁器的最佳化功能搭配使用,以減少最終建置中包含的 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,請安裝 Node.js ,它會自動包含 npm。
大多數開發人員在安裝 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 載入「city」文件。
// 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 與 Rollup 結合使用
Firebase 應用程式和 Rollup 不需要特定配置。本節介紹一般 Rollup 配置。
第一步是安裝 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 載入「city」文件。
// 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 載入「city」文件。
// 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 以進行生產的更多信息,請參閱有關縮小和其他優化的官方文件。