参数解析-commander
https://www.npmjs.com/package/commander
loading效果
ora
https://www.npmjs.com/package/ora
咨询交互
inquirer
https://www.npmjs.com/package/inquirer
克隆仓库
https://www.npmjs.com/package/download-git-repo
注意需要在入口文件顶部指定#!/usr/bin/env node
告诉系统使用node运行,否则报错
npm
package.json
- files: 可选配置项,指定发包时要包含的文件,如果不指定默认是
*
,https://docs.npmjs.com/cli/v8/configuring-npm/package-json#files - bin: 简单来说就是配置可执行文件到系统Path,这样就可以直接用配置的名字执行该文件。
https://docs.npmjs.com/cli/v8/configuring-npm/package-json#bin
- main: 默认是
index.js
,指定当使用者require的时候的入口文件
corner-cli
#!/usr/bin/env node
const commander = require('commander')
const { resolve } = require('path')
const commandList = [
{
name: 'create',
argument: '<name>',
alias: 'c',
actions: require(resolve(__dirname, './src/create.js'))
}
]
const program = new commander.Command()
commandList.forEach(cmd => {
program.command(cmd.name).argument(cmd.argument).action(cmd.actions)
})
program.command('create').argument('<name>').alias('c').action()
program.parse(process.argv)
const inquirer = require('inquirer')
const ora = require('ora')
const download = require('download-git-repo')
const prompt = [
{
type: 'rawlist',
name: 'template',
message: '请选择项目模板',
choices: ['vue3-vite-template', 'pkg-template']
}
]
function load(dirName, template) {
const spinner = ora(`Downloadinging ${template}`).start();
download(`direct:git@github.com:adjfks/${template}.git`, dirName, { clone: true }, (err) => {
spinner.stop();
// if (err) return console.log(`下载失败,请稍后重试`)
console.log(`${template} download successfully\n cd ${dirName}\n pnpm install\n pnpm run dev`);
});
}
module.exports = (name) => {
inquirer
.prompt(prompt)
.then((answers) => {
const template = answers.template
load(name, template)
})
.catch((error) => {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
console.log('当前环境不支持该CLI');
} else {
// Something else went wrong
console.log(`发生错误,请重试!`);
}
});
}