定製你的 CLI,一鍵生成項目

clipboard.png

背景

工做中, 咱們不免會遇到須要本身搭建腳手架的場景, 現成的腳手架有不少, 好比 create-react-app, vue-cli, 能覆蓋大部分的須要。 可是也要不少不便利的地方, 咱們須要本身定製一些配置, 又不想用 rewired or eject, 這個時候就須要本身手動搭建,可是從頭搭建又很繁瑣, 我本身搭建過幾個項目, 每次須要新建的時候就很煩, 那有沒有比較便利的方式呢? javascript

有的。前端

今天這篇, 我就告訴你如何定製本身的 cli, 擺脫從0 搭建項目的困擾。vue

// 要發佈的時候看到有個老哥好像發過一篇相似的文章了, 不過無所謂了, 我會從個人角度出發, 告訴你們如何一步一步定製本身的cli.java

首先放一下我本身作的cli 工具包地址: https://www.npmjs.com/package...node

如何使用:react

npm install create-my-project-cli
    
    create-my-project init project
    
    cd project
    
    yarn && yarn start

正文

要達到這樣的效果, 首先須要定製命令。git

定製命令

這個腳本就是你執行命令以後執行的邏輯,要執行的命令就定義在 package.json 中的 bin 字段裏:github

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

這個 "create-project" 就是命令的名字。vue-cli

這是package.json 的所有內容:npm

{
  "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://segmentfault.com/a/11...

他對這幾個命令都有解釋, 我就不贅述了。

結語

定製一套本身cli, 能在往後須要的時候幫你節省不少時間, 你也能夠不斷的完善本身的cli, 讓你的這個工具更強更好用。

文中我提供的react 模版包含了最經常使用的功能和優化, 有興趣能夠下載下來把玩一下。

謝謝。

下面是個人公衆號: 前端e進階

有新內容會第一時間更新在這裏, 但願你們多多關注, 觀看最新內容。

clipboard.png

推薦一個工具

樓主寫完博客通常都會往不一樣的平臺上發, 手動搬運很煩, 費時費力, 這幾天恰好看到出了一個新的工具能夠解決這個問題:

https://openwrite.cn/

clipboard.png

在這裏編輯完文章以後, 能夠一鍵發佈到你定義的全部平臺, 很方便, 你們有空能夠看看。

相關文章
相關標籤/搜索