对于A->b->c这一类的流程事件,可以采用分解这些事件,当需要用到这些事件操作时,我们将操作插入到核心事件完成所需要的不同步骤中。
实现一个流程处理函数
src/core/ware.ts
/**
* 中间件方法类型
*/
export type Middleware<S> = (context: S) => Promise<void> | void
/**
* 中间件类
*/
export class Ware<S>{
private readonly middlewares: Array<Middleware<S>> = []
/**
* 注入中间件方法
* @param middleware
*/
use(middleware: Middleware<S>): Ware<S> {
this.middlewares.push(middleware)
return this
}
/**
* 执行所有中间件方法
* @param context
*/
async run(context: S): Promise<void> {
return await this.middlewares.reduce(
(pre, current) => pre.then(() => current(context)),
Promise.resolve())
}
}
创建cli主方法
src/init/index.ts
import { Ware } from '../core/ware'
/**
* 上下文对象类型
*/
export interface Context {
name: string
}
/**
* Ware实例
*/
const creator = new Ware<Context>()
// 注入方法一 打印当前上下文对象的 name
creator.use(async (context) => {
console.log(context.name)
})
// 注入方法二 修改当前上下文对象的 name
creator.use(async (context) => {
context.name = 'hello context'
})
// 注入方法三 打印当前上下文对象的 name
creator.use(async (context) => {
console.log(context.name)
})
/**
* CLI 主函数
*/
export const init = () => {
// 定义上下文对象
const context: Context = {
name: 'hello cli'
}
// 执行所有中间件方法
creator.run(context)
}
暴露模块方法
src/index.ts
export { init } from './init'
引用且执行
import { init } from './index'
// 执行CLI 主函数
init()Ï
运行测试
# 编译文件
yarn build
# cli工具名称
<projectName>
# 输出结果
# hello cli
# hello context
到此cli脚手架主体框架基本完成,后面会介绍命令行交互部分内容