用 TypeScript 編寫 Claude Code mod
1. 先做一個行為
先實作 /hello 指令,再增加儲存、背景工作或連網。使用支援 mods 的 Claude Code 版本;線上範例與本機不同時,以安裝版本產生的宣告為準。
2. 建立三個檔案
把 manifest 放在 .claude-plugin/plugin.json,模組清單放在 hooks/hooks.json,入口放在 hooks/register.tsx。modules 的路徑相對於 hooks.json。起手式產生器 選擇 slash-command 可下載三個檔案。
3. 註冊處理函式
以 type-only import 引入 claude-code 的 Register 型別。在 session.start 註冊指令,在 command.run 處理指令。next(e) 保留原事件流程;指令處理函式回傳結果供工作階段顯示。不要只為型別引入 Node runtime 相依套件。
4. 本機驗證
在可信的測試專案載入外掛目錄,檢查 CLI 寫出的 .claude-plugin/types 宣告,用 claude plugin validate 加外掛路徑驗證。測試 /hello、熱重載與停用。結構驗證不能取代執行時行為測試。
5. 逐步擴充
介面元素來自目前 surface 的元素表,不是瀏覽器 DOM 或 React。記錄支援版本、權限、安裝與移除方式;分享前測試失敗路徑與資源釋放。
import type { Register } from "claude-code";
export const register: Register = (on) => {
on("session.start", async ($, e, next) => {
await $.command.register({ name: "hello", description: "Say hello" });
return next(e);
});
on("command.run", { command: "hello" }, async () => ({ text: "Hello" }));
};