Appearance
游戏项目中,图片资源的预加载依赖一份静态清单文件 index.ts。每次添加或删除资源都需要手动更新这份清单,容易遗漏。本节演示如何用 Kiro 的 agent hooks 机制,分别为资源新增和删除两种事件创建自动化处理钩子,让 Kiro 在文件变动时自动维护 index.ts。你将学会通过自然语言描述生成 hook 配置,以及手动复制现有 hook 并编辑为新钩子的两种方式。
用 Hooks 自动管理资源文件
本节假设你已完成前置模块。之前我们已经:
接下来,我们用 Kiro 设置一个自动化钩子,消除游戏开发中的重复样板工作。
理解问题
打开 client/src/systems/preloader-system.ts。这是一个独立的系统模块,负责在游戏启动前预加载所有资源,设计上与各游戏组件完全解耦——组件本身无需手动调用预加载接口。
这个解耦设计很干净,但引入了一个潜在问题:开发者添加新组件时,可能会忘记把新资源加入 /client/src/assets/index.ts 这份静态清单。
我们来创建自动化 hooks 来解决这个问题。
创建资源索引 Hook
点击 IDE 侧边栏的 Kiro 幽灵图标,打开 Kiro 面板。找到 "Agent Hooks" 区域,点击 + 开始创建新 hook。
用自然语言描述你想要的行为:
When a file is created in the assets folder,
ensure that the assets folder index.ts file is
appropriately updatedKiro 会把你的自然语言转换为 hook 配置文件,保存在 .kiro/hooks 目录下。生成的配置大致如下:
json
{
"name": "Image Asset Indexer",
"description": "Automatically adds references to newly added image files in the assets folder to the index.ts file",
"version": "1",
"when": {
"type": "fileCreated",
"patterns": [
"client/src/assets/*.png",
"client/src/assets/*.jpg",
"client/src/assets/*.jpeg",
"client/src/assets/*.gif",
"client/src/assets/*.svg"
]
},
"then": {
"type": "askAgent",
"prompt": "A new image file has been added to the assets folder. Please update the index.ts file in the assets folder to include a reference to this new image. First, check the current structure of the index.ts file to understand how images are referenced. Then add an appropriate export statement for the new image file following the existing pattern. Make sure to maintain alphabetical order if that's the current convention."
}
}创建资源删除 Hook
有了第一个 hook 的模板,你也可以直接在 .kiro/hooks 目录下手动创建新文件,而不必每次都通过 Kiro 生成。
复制刚才的 hook 文件,保存为 image-asset-remover.kiro.hook,内容修改如下:
json
{
"name": "Image Asset Remover",
"description": "Automatically removes references to newly deleted image files in the assets folder to the index.ts file",
"version": "1",
"when": {
"type": "fileDeleted",
"patterns": [
"client/src/assets/*.png",
"client/src/assets/*.jpg",
"client/src/assets/*.jpeg",
"client/src/assets/*.gif",
"client/src/assets/*.svg"
]
},
"then": {
"type": "askAgent",
"prompt": "An image file has been removed from the assets folder. Please update the index.ts file in the assets folder to remove any references to this removed image."
}
}此时 Kiro 面板的 "Agent Hooks" 区域应显示两个已配置的 hook。
测试效果
将一张图片拖入 client/src/assets 目录,你会看到资源索引 hook 自动触发,Kiro 更新 index.ts。
然后删除这张图片,资源删除 hook 会自动清理 index.ts 中对应的引用。
本节小结
Agent hooks 既能节省重复操作的时间,也能提高样板代码的准确性——不再有"忘记更新清单"的问题。
下一节:用 MCP 扩展 Kiro 能力
常见问题
Q:Hook 触发了,但 Kiro 没有正确更新 index.ts,怎么排查?
A:检查 hook 的 patterns 是否匹配你实际的文件路径,路径大小写需要一致。另外查看 then.prompt 是否足够具体——如果 prompt 没有说明 index.ts 的位置或引用格式,Kiro 可能生成错误的内容。
Q:可以为同一事件创建多个 hook 吗?
A:可以。多个 hook 会按文件名排序依次触发。注意每次 hook 触发的 agent prompt 动作都会消耗 credits,高频事件要控制 hook 的数量和 prompt 复杂度。
Q:Hook 文件应该提交到版本库吗?
A:建议提交。.kiro/hooks 目录存放的是团队约定的自动化规则,纳入版本控制后,团队所有成员都能享受相同的自动化保障,新成员也可以直接获得完整配置。