前言
本文主要重点在于实战代码,原理性的东西相信大家都能在其他地方搜到就不讲了
代码部分
工程目录
package.json
可以直接负责,也可以 npm init 。但是其中 bin 语句必不可少下面会讲解到
{
"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);
具体为啥这么写可以看下其他大神文章我讲下注意事项
- 这里是是我的github 地址,语法糖 [作者]/[仓库名]也支持其他仓库 更多请查看 download-git-repo 这个库
- 还有就是我们对应的github仓库package.json 也要改 因为这里传入三个参数 一个是 name ,一个是 description,最后是 author
发 npm 包
npm login && npm publish 然后发布成功
下载使用
- 以我这个例子 npm i webpack4_cli_yhy -g 安装完以后随便找个文件夹
- cd mycli 并打开 如下图
左边是我 github的仓库里的内容同时可以看到我们刚才控制台输入的内容在这里显示出来了 - 以后更新只需要更新 github里的东西就行了 如果你想扩展自己的脚手架那么每次更新完都要重新发 npm 包
结语
写的比较仓促多多包涵