你们新年好!
年前在工做中接到任务要开发一个本身的CLI,便去了解了一下。发现并不难,只需运用nodejs的相关api便可。node
目前实现的功能为:git
下面将分步去解析一个CLI的制做过程,也算是一次记录回忆的过程。github
用 npm init 生成项目的package.json文件。而后编辑该文件主要加上npm
"bin": {
"jsm": "./bin/jsm.js"
},
复制代码
而后在当前目录建立你本身的脚本文件,对应上述配置为 mkdir bin && touch bin/jsm.js
编辑建立好的文件,加上json
#!/usr/bin/env node
console.log('Hello CLI')
复制代码
接下来在项目的根目录运行一下 npm i -g
, 如今就能够在命令行使用jsm命令了。
注意: 必定要在开头加上#!/usr/bin/env node
, 不然没法运行。api
详解:package.json文件只有加上了bin字段,才能在控制台使用你的命令,对应的这里的命令就是jsm,对应的执行文件为bin/jsm.js。 其实"jsm"命令就是 "node bin/jsm.js" 的别称,只有你用npm i -g全局安装后才能够用,开发的过程当中直接用node bin/jsm.js便可。
app
一个CLI须要经过命令行输入各类参数,能够直接用nodejs的process相关api进行解析,可是更推荐使用commander这个npm包能够大大简化解析的过程。 npm i commander
安装, 而后更改以前的脚本文件添加函数
const program = require('commander');
program
.command('create <type> [name] [otherParams...]')
.alias('c')
.description('Generates new code')
.action(function (type, name, otherParams) {
console.log('type', type);
console.log('name', name);
console.log('other', otherParams);
// 在这里执行具体的操做
});
program.parse(process.argv);
复制代码
如今在终端执行一下 node bin/jsm.js c component myComponent state=1 title=HelloCLI
应该就能看到输入的各类信息信息了。至此命令解析部分就基本ok了,其余更多的用法能够参考官方例子ui
详解:command第一个参数为命令名称,alias为命令的别称, 其中<>包裹的为必选参数 []为选填参数 带有...的参数为剩余参数的集合。
spa
接下来须要根据上一步输入的命令去作一些事情。具体到一个脚手架CLI通常主要作两件事,快速的生成一个新项目和快速的建立对应的样板文件。 既然须要建立文件就少不了对nodejs的fs模块的运用,这里用的一个加强版的fs-extra
下面封装两个经常使用的文件处理函数
//写入文件
function write(path, str) {
fs.writeFileSync(path, str);
}
//拷贝文件
function copyTemplate(from, to) {
from = path.join(__dirname, from);
write(to, fs.readFileSync(from, 'utf-8'));
}
复制代码
命令以下
program
.command('new [name]')
.alias('n')
.description('Creates a new project')
.action(function (name) {
const projectName = name || 'myApp';
init({ app: projectName })
});
复制代码
init函数主要作了两件事:
const fs = require('fs-extra');
const chalk = require('chalk');
const {basename, join} = require('path');
const readline = require('readline');
const download = require('download-git-repo');
const ora = require('ora');
const vfs = require('vinyl-fs');
const map = require('map-stream');
const template = 'stmu1320/Jsm-boilerplate';
// 建立函数
function createProject(dest) {
const spinner = ora('downloading template')
spinner.start()
if (fs.existsSync(boilerplatePath)) fs.emptyDirSync(boilerplatePath)
download(template, 'boilerplate', function (err) {
spinner.stop()
if (err) {
console.log(err)
process.exit()
}
fs
.ensureDir(dest)
.then(() => {
vfs
.src(['**/*', '!node_modules/**/*'], {
cwd: boilerplatePath,
cwdbase: true,
dot: true,
})
.pipe(map(copyLog))
.pipe(vfs.dest(dest))
.on('end', function() {
const app = basename(dest);
const configPath = `${dest}/config.json`;
const configFile = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
configFile.dist = `../build/${app}`;
configFile.title = app;
configFile.description = `${app}-project`;
write(configPath, JSON.stringify(configFile, null, 2));
// 这一部分执行依赖包安装,具体代码请查看文末连接
message.info('run install packages');
require('./install')({
success: initComplete.bind(null, app),
cwd: dest,
});
})
.resume();
})
.catch(err => {
console.log(err);
process.exit();
});
})
}
function init({app}) {
const dest = process.cwd();
const appDir = join(dest, `./${app}`);
createProject(appDir);
}
复制代码
生成样板文件这一部分,其实就是拷贝一个文件到指定的地方而已,固然还应该根据参数改变文件的具体内容。
program
.command('create <type> [name] [otherParams...]')
.alias('c')
.description('Generates new code')
.action(function (type, name, otherParams) {
const acceptList = ['component', 'route']
if (!acceptList.find(item => item === type)) {
message.light('create type must one of [component | route]')
process.exit()
}
const params = paramsToObj(otherParams)
params.name = name || 'example'
generate({
type,
params
})
});
//生成文件入口函数
function generate({type, params}) {
const pkgPath = findPkgPath(process.cwd())
if (!pkgPath) {
message.error('No \'package.json\' file was found for the project.')
process.exit()
}
const dist = path.join(pkgPath, `./src/${type}s`);
fs
.ensureDir(dist)
.then(() => {
switch (type) {
case 'component':
// 具体代码请查看文末连接
createComponent(dist, params);
break;
case 'route':
createRoute(dist, params);
break;
default:
break;
}
})
.catch(err => {
console.log(err);
process.exit(1);
});
}
复制代码
到这里一个基本的脚手架CLI就差很少了,剩下的是帮助信息等友好提示的东西了。文章的全部源码点击这里
也欢迎你们安装试用一下 npm i -g jsm-cli
。