29 lines
1.1 KiB
TypeScript
29 lines
1.1 KiB
TypeScript
// 从内置hooks目录中获取所有hooks并注册到HookBus
|
||
|
||
import path from 'node:path';
|
||
import fs from 'node:fs';
|
||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||
import { hooks } from './index.js';
|
||
|
||
// 这里可以自动扫描hooks目录下的所有文件并导入它们,假设每个文件都默认导出一个函数来注册hook
|
||
|
||
const getAllHooks = async () => {
|
||
// 动态读取hooks目录下的所有 .hooks.ts 结尾的文件
|
||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||
const hooksDir = path.join(__dirname); // hooks 目录即当前目录
|
||
const hookFiles = fs.readdirSync(hooksDir).filter(file => file.endsWith('.hooks.ts'));
|
||
return Promise.all(
|
||
hookFiles.map(async (file) => {
|
||
const mod = await import(pathToFileURL(path.join(hooksDir, file)).href);
|
||
return mod.default;
|
||
})
|
||
);
|
||
}
|
||
|
||
export const registerHooks = async () => {
|
||
const hookModules = await getAllHooks();
|
||
for (const hookModule of hookModules) {
|
||
// 每个hook模块默认导出一个函数,调用它并传入hooks实例
|
||
hookModule(hooks);
|
||
}
|
||
} |