创建npm包
mkdir xwypack-git-express-api-cli
npm init
名称为:xwypack-git-express-api-cli
npm install commander git-clone shelljs open
npm配置
{
"name": "xwypack-git-express-api-cli",
"version": "1.0.0",
"description": "简单的创建expressapi项目工具",
"main": "index.js",
"bin": {
"gitexpressapicli": "bin/index.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT",
"dependencies": {
"commander": "^11.1.0",
"git-clone": "^0.2.0",
"open": "^8.4.2",
"shelljs": "^0.8.5"
}
}
创建bin/index.js
#!node
const commander=require('commander')
const shell=require('shelljs')
const gitClone=require('git-clone')
const {spawn}=require('child_process')
const open=require('open')
const {readFileSync } = require('fs')
const path = require('path')
let packagePath=path.join(__dirname,'../package.json');
// console.log(packagePath)
// packagePath='../package.json';
const pkg=JSON.parse(readFileSync(packagePath));
commander.version(pkg.version)
commander.command('new <name>')
.description('创建项目')
.action(name=>{
let gitUrl=`git@gitee.com:HUJIAFANGFUJIDDD/realworld-api-express.git`;
gitClone(gitUrl,`./${name}`,()=>{
// shell.rm('-rf',`${name}/.git`);
// shell.cd(name);
// shell.exec('npm install');
console.log(`
创建项目${name}成功
cd ${name} 进入项目
npm install
unrar run 启动项目
unrar start 预览项目
`)
})
})
commander.command('run')
.description('运行项目')
.action(()=>{
// let cp=spawn('npm',['run','start'])
// cp.stdout.pipe(process.stdout)
// // cp.stdin.pipe(process.stdin)
// cp.stderr.pipe(process.stderr)
// cp.on('close',()=>{
// console.log(`运行项目成功`)
// })
shell.exec('npm run start')
})
commander.command('start')
.description('预览项目')
.action(()=>{
open('http://localhost:8080')
console.log(`预览项目`)
})
commander.command('test')
.description('测试命令')
.action(()=>{
console.log(`测试命令打印成功`)
})
commander.parse(process.argv)
// console.log('你好2');
测试与发布npm包
npm link
npm unlink -g xwypack-git-express-api-cli
unrar new expess_demo
unrar test
unrar run
unran start
npm login
npm publish
使用npm包
npm install -g xwypack-git-express-api-cli
gitexpressapicli
gitexpressapicli run
gitexpressapicli start