> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Deployer Deployer 會封裝程式碼、管理環境檔案,並使用 Hono 框架提供應用程式,以處理獨立 Mastra 應用程式的部署。具體實作必須針對特定部署目標定義 deploy 方法。 ## 使用範例 若要建立自訂 deployer,可以擴充抽象 `Deployer` 類別,並以特定部署邏輯實作 `deploy` 方法。範例如下: ```typescript import { Deployer } from '@mastra/deployer' class CustomDeployer extends Deployer { constructor() { super({ name: 'custom-deployer' }) } async deploy(outputDirectory: string): Promise { // Prepare the output directory await this.prepare(outputDirectory) // Bundle the application await this._bundle('server.ts', 'mastra.ts', outputDirectory) // Custom deployment logic } } ``` ## 參數 ### 建構函式參數 **args** (`object`): Deployer 的設定選項。 **args.name** (`string`): deployer 執行個體的唯一名稱。 ### deploy 參數 **outputDirectory** (`string`): 輸出已封裝且可部署應用程式的目錄。 ## 方法 **getEnvFiles** (`() => Promise`): 傳回部署期間要使用的環境檔案清單。預設會尋找 '.env.production' 與 '.env' 檔案。 **deploy** (`(outputDirectory: string) => Promise`): 必須由子類別實作的抽象方法。處理應用程式部署至指定輸出目錄的處理程序。 ## 繼承自 bundler 的方法 Deployer 類別會繼承 Bundler 類別的下列主要方法: **prepare** (`(outputDirectory: string) => Promise`): 清理輸出目錄並建立必要的子目錄,以準備輸出目錄。 **writePackageJson** (`(outputDirectory: string, dependencies: Map) => Promise`): 在輸出目錄中產生包含指定相依套件的 package.json 檔案。 **\_bundle** (`(serverFile: string, mastraEntryFile: string, outputDirectory: string, bundleLocation?: string) => Promise`): 使用指定的伺服器檔案與 Mastra 進入點檔案封裝應用程式。 ## 核心概念 ### 部署生命週期 Deployer 抽象類別會實作結構化的部署生命週期: 1. **初始化**:使用名稱初始化 deployer,並建立 Deps 執行個體以管理相依套件。 2. **環境設定**:`getEnvFiles` 方法會找出部署期間要使用的環境檔案(.env.production、.env)。 3. **準備**:`prepare` 方法(繼承自 Bundler)會清理輸出目錄並建立必要的子目錄。 4. **封裝**:`_bundle` 方法(繼承自 Bundler)會封裝應用程式的程式碼及其相依套件。 5. **部署**:子類別會實作抽象 `deploy` 方法,以處理實際部署流程。 ### 環境檔案管理 Deployer 類別透過 `getEnvFiles` 方法內建環境檔案管理支援。此方法會: - 依照預先定義的順序尋找環境檔案(.env.production、.env) - 使用 FileService 尋找第一個存在的檔案 - 傳回包含找到之環境檔案的陣列 - 找不到任何環境檔案時傳回空陣列 ```typescript getEnvFiles(): Promise { const possibleFiles = ['.env.production', '.env.local', '.env']; try { const fileService = new FileService(); const envFile = fileService.getFirstExistingFile(possibleFiles); return Promise.resolve([envFile]); } catch {} return Promise.resolve([]); } ``` ### 封裝與部署的關係 Deployer 類別擴充 Bundler 類別,在封裝與部署之間建立清楚的關係: 1. **以封裝為先決條件**:封裝是部署的先決步驟,會將應用程式的程式碼封裝為可部署的格式。 2. **共用基礎架構**:封裝與部署共用相依套件管理及檔案系統操作等基礎架構。 3. **專用部署邏輯**:封裝著重於程式碼封裝,而部署則加入環境專屬邏輯,以部署封裝後的程式碼。 4. **可擴充性**:抽象 `deploy` 方法可用來為不同目標環境建立專用 deployer。