定制你的-CLI一键生成项目

4次阅读

共计 3466 个字符,预计需要花费 9 分钟才能阅读完成。

背景

工作中,我们难免会遇到需要自己搭建脚手架的场景,现成的脚手架有很多,比如 create-react-app, vue-cli,能覆盖大部分的需要。但是也要很多不便利的地方,我们需要自己定制一些配置,又不想用 rewired or eject,这个时候就需要自己手动搭建,但是从头搭建又很繁琐,我自己搭建过几个项目,每次需要新建的时候就很烦,那有没有比较便利的方式呢?

有的。

今天这篇,我就告诉你如何定制自己的 cli, 摆脱从 0 搭建项目的困扰。

// 要发布的时候看到有个老哥好像发过一篇类似的文章了,不过无所谓了,我会从我的角度出发,告诉大家如何一步一步定制自己的 cli.

首先放一下我自己做的 cli 工具包地址:https://www.npmjs.com/package…

如何使用:


```
sudo npm install create-my-project-cli -g

mkdir temp && cd temp
 
create-project project
 
cd project 
 
yarn && yarn start

```

正文

要达到这样的效果,首先需要定制命令。

定制命令

这个脚本就是你执行命令之后执行的逻辑,要执行的命令就定义在 package.json 中的 bin 字段里:

    
    "bin": {"create-project": "index.js"},
    

这个 "create-project" 就是命令的名字。

这是 package.json 的全部内容:

{
  "name": "create-my-project-cli",
  "version": "1.0.4",
  "description": "A cli to create project quickly...",
  "main": "index.js",
  "scripts": {
    "lint": "eslint ./ --ext .js,.tsx,.ts",
    "lint:fix": "yarn lint --fix"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/beMySun/create-my-project-cli.git"
  },
  "bin": {"create-project": "index.js"},
  "author": "KK",
  "license": "ISC",
  "bugs": {"url": "https://github.com/beMySun/create-my-project-cli/issues"},
  "homepage": "https://github.com/beMySun/create-my-project-cli#readme",
  "dependencies": {
    "chalk": "^2.4.2",
    "commander": "^3.0.1",
    "download": "^7.1.0",
    "download-git-repo": "^2.0.0",
    "handlebars": "^4.2.1",
    "inquirer": "^7.0.0",
    "ora": "^4.0.0",
    "symbols": "^0.0.6"
  },
  "devDependencies": {
    "babel-eslint": "^10.0.3",
    "eslint": "^6.4.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.14.3"
  }
}

编写 node 脚本

执行 create-project 命令之后,就开始执行这段脚本,本质上就是 下载你定义好的项目模版到你本地

下面就看该怎么实现这段逻辑, 算了,不绕弯子了,逻辑也不复杂,直接贴代码吧:

#!/usr/bin/env node

const fs = require('fs');
const program = require('commander');
const chalk = require('chalk');
const download = require('download-git-repo');
const inquirer = require('inquirer');
const ora = require('ora');
const symbols = require('log-symbols');
const handlebars = require('handlebars');

program
  .version(require('./package').version, '-v, --version')
  .command('<name>')
  .action(name => {if (!fs.existsSync(name)) {
      inquirer
        .prompt([
          {
            name: 'templateType',
            message: 'which template type you need to create?',
            type: 'list',
            choices: ['react', 'rollup']
          },
          {
            name: 'description',
            message: 'please enter a description:'
          },
          {
            name: 'author',
            message: 'please enter a author:'
          }
        ])
        .then(answers => {const spinner = ora('downloading template...');
          spinner.start();
          const downloadPath = `direct:https://github.com/beMySun/${answers.templateType}-project-template.git#master`;
          download(downloadPath, name, { clone: true}, err => {if (err) {spinner.fail();
              console.error(
                symbols.error,
                chalk.red(`${err}download template fail,please check your network connection and try again`)
              );
              process.exit(1);
            }
            spinner.succeed();
            const meta = {
              name,
              description: answers.description,
              author: answers.author
            };
            const fileName = `${name}/package.json`;
            const content = fs.readFileSync(fileName).toString();
            const result = handlebars.compile(content)(meta);
            fs.writeFileSync(fileName, result);
          });
        });
    } else {console.error(symbols.error, chalk.red('project has existed !!!'));
    }
  })
  .on('--help', () => {console.log('Examples:');
  });

program.parse(process.argv);

这里我提供了两个模版,一个是 react , 一个 rollup, 不同的选择会输出不同的模版。

这两套模版都是首先定义好的,会根据你的选择来确定下载哪一个。

源代码分别在:

  • https://github.com/beMySun/re…
  • https://github.com/beMySun/ro…

上面命令都是基础命令,没什么好解释的,如果哪里不清楚,可以参考这位老哥的:

https://segmentfault.com/a/11…

他对这几个命令都有解释,我就不赘述了。

结语

定制一套自己 cli,能在日后需要的时候帮你节省很多时间,你也可以不断的完善自己的 cli, 让你的这个工具更强更好用。

文中我提供的 react 模版包含了最常用的功能和优化,有兴趣可以下载下来把玩一下。

谢谢。

下面是我的公众号:前端 e 进阶

有新内容会第一时间更新在这里,希望大家多多关注,观看最新内容。

推荐一个工具

楼主写完博客一般都会往不同的平台上发,手动搬运很烦,费时费力,这几天刚好看到出了一个新的工具可以解决这个问题:


https://openwrite.cn/

在这里编辑完文章之后,可以一键发布到你定义的所有平台,很方便,大家有空可以看看。

正文完
 0