如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/<package>,
結果如下:
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處理 。http://www.lxweimin.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:? 給命令行輸出文字上色