如何发布一个cli脚手架

如react-cli,vue-cli等脚手架工具,能够包裹一些常用的东西,方便开发使用。
下面就介绍下cli脚手架如何制作,以制作react-cli为例。

一、简单 node 命令行

1、初始化项目

npm init

执行上面的命令,自动生成package.json文件,详见,项目名字就叫react-cli。

2、创建运行命令的脚本 bin/index.js

#! /user/bin/env node

console.log('Hello node cli');

然后在控制台中执行node bin/index.js就会输出Hello node cli

3、链接到npm

在已经创建好的package.json文件中加入下面的字段:

... 

"bin": {
  "react-cli": "./bin/index"
}
...

package.json中有一个"bin"字段,配置后才可以在控制台使用你的命令。

4、全局安装你的包

要使react-cli作为全局命令,还需要将它安装到全局,有两种方式:npm link or npm install . -g
P.S.换个新的目录,执行 react-cli 看看成功了没~

npm link 作用 :执行命令后,react-cli会根据package.json上的配置,被链接到全局,路径是{prefix}/node_modules/
结果如下:
C:\Users\fineday\AppData\Roaming\npm\react-cli -> C:\Users\fineday\AppData\Roaming\npm\node_modules\react-cli\bin\index.js
C:\Users\fineday\AppData\Roaming\npm\node_modules\react-cli -> D:\yhwork\project\react-cli

我们可以使用npm config get prefix命令获取到prefix的值。

$ npm config get prefix
C:\Users\fineday\AppData\Roaming\npm

下面是bin/index.js文件 (能实现基础功能)

#!usr/bin/env node 
        // env的主要目的就是让我们的脚本在不同的操作系统上都能够正常的被解释,启动。在该文件中指定为node为解释环境。   
const Promise = require('bluebird),
        fs = Promise.promisifyAll(require('fx-extra')),
        chalk = require('chalk'),
        program = require('commander');
cosnt ver = require('../package.json').version;
program
    .version(ver)
    .usage('react-cli usage')
    .parse(process.argv)
let dPath = './',
    srcPath = __dirname.replace('\\bin','') + '\\templates';
if(program.args[0] === undefined) {
    console.log(chalk.red('project dirname missing');
}
else dPath = program.args[0]
function generateCli(destPath) {
    return fs.copyAsync(srcPath,destPath,{clobber: true})
            .then(() => {
                    console.log(chalk.green('success'))
            }.catch((er) => {
                console.log(chalk.red(`cd ${err}`)
            }
}

generateCli(dPath);    

ps:
fs-extra :系统fs模块的扩展,提供了更多便利的 API,并继承了fs模块的 API,该API可以被bluebird的promise处理 。https://www.jianshu.com/p/d6990a03d610

commander : 编写node命令行的神器,可以帮助我们简化很多操作       https://github.com/tj/commander.js/blob/HEAD/Readme_zh-CN.md

bluebird : 是一个promise工具库,将异步回调操作转为promise                                  https://www.ibm.com/developerworks/cn/web/wa-lo-use-bluebird-implements-power-promise/index.html

chalk:  给命令行输出文字上色

你可能感兴趣的:(如何发布一个cli脚手架)