> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/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. **準備**:從 Bundler 繼承的 `prepare` 方法會清理輸出目錄並建立所需的子目錄。 4. **封裝**:從 Bundler 繼承的 `_bundle` 方法會封裝應用程式程式碼及其依賴套件。 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。