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 生態系統提供許多高品質的模組整合工具。本指南著重於說明如何搭配 webpack、Rollup 和 esbuild 使用 Firebase。
開始探索
本指南要求您在開發環境中安裝 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
檔案視為進入點,因為它會開始匯入應用程式所有必要程式碼。模組組合器會使用這個進入點檔案來開始繫結程序。
搭配 webpack 使用 Firebase
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
的檔案,其中包含封裝的應用程式和依附元件程式碼。
如要進一步瞭解如何針對實際工作環境最佳化 Web Pack 版本,請參閱「模式」設定設定的官方說明文件。
將 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 做為開發依附元件。
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
的檔案,其中包含封裝的應用程式和依附元件程式碼。
如要進一步瞭解如何針對實際工作環境最佳化建構版本,請參閱官方說明文件的壓縮和其他最佳化功能。