node 生成 cli 实战

前言

本文主要重点在于实战代码,原理性的东西相信你们都能在其余地方搜到就不讲了javascript

代码部分

工程目录java

截图

package.json

能够直接负责,也能够 npm init 。可是其中 bin 语句必不可少下面会讲解到node

{
"name": "webpack4_cli_yhy",
"version": "1.0.2",
"description": "test-cli",
"main": "./index.js",
"keywords": [
  "cli"
],
"bin": {
  "webpack4-cli": "./index.js"
},
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
  "chalk": "^2.4.1",
  "commander": "^2.19.0",
  "download-git-repo": "^1.1.0",
  "handlebars": "^4.0.12",
  "inquirer": "^6.2.0",
  "log-symbols": "^2.2.0",
  "ora": "^3.0.0"
}
}

复制代码

index.js

#!/usr/bin/env node
const fs = require('fs');
const program = require('commander');
const download = require('download-git-repo');
const handlebars = require('handlebars');
const inquirer = require('inquirer');
const ora = require('ora');
const chalk = require('chalk');
const symbols = require('log-symbols');

program.version('1.0.0', '-v, --version')
   .command('init <name>')
   .action((name) => {
       if(!fs.existsSync(name)){
           inquirer.prompt([
               {
   				name: 'description',
   				message: '请输入项目描述'
   			},
   			{
   				name: 'author',
   				message: '请输入做者名称'
   			}
           ]).then((answers) => {
               const spinner = ora('正在下载模板...');
               spinner.start();
   			download('yuhaiyang1/webpack4', name, (err) => {
                   if(err){
                       spinner.fail();
                       console.log(symbols.error, chalk.red(err));
                   }else{
                       spinner.succeed();
                       const fileName = `${name}/package.json`;
                       const meta = {
                           name,
                           description: answers.description,
                           author: answers.author
                       }
                       if(fs.existsSync(fileName)){
                           const content = fs.readFileSync(fileName).toString();
                           const result = handlebars.compile(content)(meta);
                           fs.writeFileSync(fileName, result);
                       }
                       console.log(symbols.success, chalk.green('项目初始化完成'));
                   }
               })
           })
       }else{
           // 错误提示项目已存在,避免覆盖原有项目
           console.log(symbols.error, chalk.red('项目已存在'));
       }
   })
program.parse(process.argv);
复制代码

具体为啥这么写能够看下其余大神文章我讲下注意事项webpack

  • 这里是是个人github 地址,语法糖 [做者]/[仓库名]也支持其余仓库 更多请查看 download-git-repo 这个库
  • 还有就是咱们对应的github仓库package.json 也要改 由于这里传入三个参数 一个是 name ,一个是 description,最后是 author

发 npm 包

npm login && npm publish 而后发布成功git

下载使用

  • 以我这个例子 npm i webpack4_cli_yhy -g 安装完之后随便找个文件夹

这个 webpack4-cli 就是你本身的package.json bin 对象

  • cd mycli 并打开 以下图
    左边是我 github的仓库里的内容同时能够看到咱们刚才控制台输入的内容在这里显示出来了
  • 之后更新只须要更新 github里的东西就好了 若是你想扩展本身的脚手架那么每次更新完都要从新发 npm 包

结语

写的比较仓促多多包涵github

相关文章
相关标签/搜索