参数解析-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

https://docs.npmjs.com/cli/v8/configuring-npm/package-json#bin

  • main: 默认是index.js,指定当使用者require的时候的入口文件

corner-cli

  1. #!/usr/bin/env node
  2. const commander = require('commander')
  3. const { resolve } = require('path')
  4. const commandList = [
  5. {
  6. name: 'create',
  7. argument: '<name>',
  8. alias: 'c',
  9. actions: require(resolve(__dirname, './src/create.js'))
  10. }
  11. ]
  12. const program = new commander.Command()
  13. commandList.forEach(cmd => {
  14. program.command(cmd.name).argument(cmd.argument).action(cmd.actions)
  15. })
  16. program.command('create').argument('<name>').alias('c').action()
  17. program.parse(process.argv)
  1. const inquirer = require('inquirer')
  2. const ora = require('ora')
  3. const download = require('download-git-repo')
  4. const prompt = [
  5. {
  6. type: 'rawlist',
  7. name: 'template',
  8. message: '请选择项目模板',
  9. choices: ['vue3-vite-template', 'pkg-template']
  10. }
  11. ]
  12. function load(dirName, template) {
  13. const spinner = ora(`Downloadinging ${template}`).start();
  14. download(`direct:git@github.com:adjfks/${template}.git`, dirName, { clone: true }, (err) => {
  15. spinner.stop();
  16. // if (err) return console.log(`下载失败,请稍后重试`)
  17. console.log(`${template} download successfully\n cd ${dirName}\n pnpm install\n pnpm run dev`);
  18. });
  19. }
  20. module.exports = (name) => {
  21. inquirer
  22. .prompt(prompt)
  23. .then((answers) => {
  24. const template = answers.template
  25. load(name, template)
  26. })
  27. .catch((error) => {
  28. if (error.isTtyError) {
  29. // Prompt couldn't be rendered in the current environment
  30. console.log('当前环境不支持该CLI');
  31. } else {
  32. // Something else went wrong
  33. console.log(`发生错误,请重试!`);
  34. }
  35. });
  36. }