Vite 插件
控制台交互、hook 顺序执行、spawnSync 进程
typescript
import { spawnSync } from 'node:child_process'
import chalk from 'chalk'
import inquirer, { QuestionCollection } from 'inquirer'
import { Plugin } from 'vite'
/*
* 我不吃牛肉!🐂 !强势支持!
* */
export function noBeef(): Plugin {
return {
name: 'beef',
buildStart: {
sequential: true,
handler: () =>
waitForWithTimeout(queryJob, () => {
console.log()
console.log(chalk.overline.red('时间到!'))
}),
},
}
}
async function queryJob() {
const CHOICES = ['nothing', 'generator proto.d'] as const
const QUESTIONS: QuestionCollection<{ job: (typeof CHOICES)[number] }>[] = [
{
type: 'list', // 列表选择类型
name: 'job', // 接收输入值的变量名
message: 'Choice an item to continue...', // 显示给用户的提示信息
choices: CHOICES, // 可选择的列表项
default: 'nothing',
},
]
return inquirer.prompt(QUESTIONS).then(({ job }) => {
switch (job) {
case 'nothing':
console.log(chalk.hex('#e36209').bgHex('#2b2d30').bold('🐂🐂 启动!'))
break
case 'generator proto.d':
spawnSync('node', ['scripts/autopb.cjs', ' -b', 'beta', 'talker.ext.proto'], {
stdio: 'inherit',
shell: true,
})
spawnSync('node', ['scripts/types-pb.cjs'], {
stdio: 'inherit',
shell: true,
})
break
}
})
}
// 接受一个 promise 函数,如果指定时间内没有完成 resolve,则直接超时跳过
function waitForWithTimeout(cb: () => Promise<any>, bounceOut: () => void, ms = 2e3) {
return new Promise<void>((resolve) => {
const timer = setTimeout(() => {
bounceOut()
resolve()
}, ms)
cb().then(() => {
clearTimeout(timer)
resolve()
})
})
}