模块机制
模块机制是 Nexus 的扩展骨架。一个「业务功能」被封装为 modules/<name>/ 目录,自带页面、服务端路由、数据库迁移与后台菜单;在 config/modules.ts 中启用后,这些资源会在构建期被聚合、运行期被加载,无需修改主应用代码。
模块结构
以 modules/example(最小可运行示例)为例:
text
modules/example/
├── nexus-module.json # 模块元信息(name / displayName / exports 指向下面各目录)
├── menu.json # 后台菜单项(title / to / icon / order)
├── pages/ # 页面(自动注册到 /modules/example/*)
│ └── index.vue
├── api/ # 服务端路由(自动注册到 /api/...)
│ └── hello.get.ts
└── migrations/ # Drizzle 迁移(启动期执行)
└── 0000_example.sqlnexus-module.json 的关键字段:
json
{
"name": "example",
"displayName": "示例模块",
"version": "1.0.0",
"exports": {
"pages": "./pages",
"api": "./api",
"migrations": "./migrations",
"menu": "./menu.json"
}
}menu.json 声明后台菜单:
json
[
{
"title": "示例模块",
"to": "/modules/example",
"icon": "lucide:box",
"order": 100
}
]启用模块
编辑 config/modules.ts,把模块名加入启用列表:
ts
export const enabledModules: string[] = [
'example',
'wechat-creator',
]每个名称对应 modules/<name>/nexus-module.json。
加载流程
text
config/modules.ts 声明启用 ['example','wechat-creator']
│
↓ 构建期(nexus.module.ts 扫描启用模块)
pages/ → 注册到 /modules/<name>/*
api/ → 注册到 /api/...
migrations/ → 由 module-migration-runner 执行
menu.json → 注入 Admin 后台菜单
│
↓ 运行期
server/plugins/module-migrations.ts 在启动时执行模块迁移(与主库迁移隔离)- 构建期聚合:
server/utils/modules/nexus.module.ts是 Nuxt 模块,在构建时把启用模块的页面、API、迁移、菜单并入主应用。 - 菜单自治:模块通过
menu.json自己声明后台入口,互不冲突。 - 迁移隔离:模块迁移由
module-migration-runner单独追踪执行,主库迁移(server/database/migrations)与模块迁移解耦,便于模块独立演进。
新增一个模块
- 在
modules/<your-module>/下创建nexus-module.json(声明 exports)。 - 按需添加
pages/、api/、migrations/、menu.json。 - 在
config/modules.ts把模块名加入enabledModules。 - 重启开发服务器,页面/API/菜单/迁移自动生效。
模块机制也是对 Coding Agent 友好的:目录边界清晰、依赖方向单一,Agent 可在
modules/<name>/内安全地新增业务,而不必理解主应用全貌。详见 AI 驱动开发。

