1. Yeoman
1.1 安装Yeoman
yarn global add yo
npm install yo -g
安装generator
yarn global add generator-node
npm install generator -g
通过yo运行generator
mkdir my-module
cd my-module
yo node
Yeoman使用步骤:
1.明确你的需求; 2.找到合适的Generator; 3.全局范围安装找到的Generator; 4.通过 Yo运行对应的Generator; 5.通过命令行交互填写选项; 6.生成你所需要的项目结构;
1.2 自定义Yeoman
创建自定义Generator模块
Generator本质上就是一个npm模块
目录结构:
新建generator项目时,名字格式必须为generator-<name>
mkdir generator-simple
cd generator-simple
yarn init
yarn add yeoman-generator
yarn link 链接到全局,使之成为全局模块包
使用方法:
yo simple
编写generator生成器(index.js
文件)
const Generator = require('yeoman-generator')
module.exports = class extends Generator {
prompting () {
return this.prompt([
{
type: 'input',
name: 'name',
message: 'Your project name',
default: this.appname
},
{
type: 'input',
name: 'description',
message: 'Your project description',
default: this.appname
}
])
.then(answers => {
this.answers = answers
})
}
writing () {
// 把每一个文件都通过模板转换到目标路径
const templates = [
// 文件模版路径
...
]
templates.forEach(item => {
// item => 每个文件路径
this.fs.copyTpl(
this.templatePath(item),
this.destinationPath(item),
this.answers
)
})
}
}
这里可以通过代码获取所有文件路径
const glob = require("glob")
const files = glob.sync("**/*.**")
console.log('files', files)
输出模版如果需要转义<,需要在后面再加个%
<link rel="icon" href="<%%= BASE_URL %>favicon.ico">
发布:如果遇到镜像问题无法发布,在发布时指定镜像源即可
yarn publish --registry=https://registry.yarnpkg.com
2. node-cli
该工具主要用到了几个插件,这里简单介绍一下:
commander:命令行输入和参数解析
chalk:设置终端样式
inquirer:交互式命令行,提问/选择
download-git-repo: 下载github代码
ora:命令行动画
搞一个Node Cli来提升工作效率
为你的团队打造一个 Node CLI 工具吧