搭建脚手架的目的:快速搭建项目的基本结构并提供项目规范和约定。
搭建 cli 脚手架
1.npm init -y // 快速初始化一个项目
2.新建命令行的入口文件 /bin/cli.js
#! /usr/bin/env node //用于解释程序的脚本
console.log('Hello World!') //为了测试是否正常
3.在package.json中新建bin对象,存放之后需要执行的js文件
{
....,
"bin": {
"temp-cli": "./bin/cli.js"
}
....
}
4.将npm包链接到全局执行环境: npm link
Mac电脑: sudo npm link
5.执行 temp-cli 命令
输出:Hello World!
6.cli 工具库简介【安装: cnpm i commander inquirer chalk download-git-repo ora 】
1)commander: 命令行交互工具 [https://github.com/tj/commander.js]
const program = require('commander');
// 获取版本信息
program.version(require('../package.json').version);
// process.argv: 可以以数组形式获取命令行参数
program.parse(process.argv);
命令:temp-cli -h
Usage: temp-cli [options]
Options:
-V, --version output the version number
-h, --help display help for command
2)inquirer: 交互式命令行工具 [https://github.com/SBoudrias/Inquirer.js]
#!/usr/bin/env node
const program = require('commander');
const inquirer = require('inquirer');
const initAction = () => {
inquirer.prompt([
{
type: 'input',
message: '请输入项目名称:',
name: 'name'
}
]).then(answers => {
console.log('项目名为:', answers.name);
console.log('正在拷贝项目,请稍等')
});
}
// 获取版本信息
program.version(require('../package.json').version);
program.command('init').description('创建项目').action(initAction);
// process.argv: 可以以数组形式获取命令行参数
program.parse(process.argv);
3)chalk:美化命令行中输出内容的样式
4)download-git-repo: 下载远程模版
5)ora: 用于显示加载中等待提示 [https://github.com/sindresorhus/ora]
7.指定 git 地址
生成需要下载指定地址的项目;需要执行 shell 脚本,cnpm i shelljs
......
const initAction = () => {
inquirer.prompt(.....).then(answers => {
console.log('项目名为:', answers.name);
console.log('正在拷贝项目,请稍等');
const remote = 'http://gogs.myhexin.com/taojinchao/check_account.git';
const curName = 'Dist';
const tarName = answers.name;
shell.exec(`
git clone ${remote} --depth=1
mv ${curName} ${tarName}
rm -rf ./${tarName}/.git
cd ${tarName}
npm i
`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`)
return
}
console.log(`${stdout}`)
console.log(`${stderr}`)
});
});
}
- 执行 temp-cli init 验证效果
发布到 npm
1.在根目录添加publish.sh
#!/usr/bin/env bash
set -e
# 修改npm源地址
npm config get registry
npm config set registry=https://registry.npmjs.org/
# 登陆输入自己的npm账号和密码,还有邮箱
echo '登录'
npm login
echo "发布中..."
npm publish
# 改回npm源地址,很多时候我们用的是淘宝镜像源
npm config set registry=https://registry.npm.taobao.org
echo -e "\n发布成功\n"
exit
2.执行 sh publish.sh
发布时遇到的问题
一、E426: 镜像源地址写成了http
二、Enter one-time password from your authenticator app
npm二次验证:需要输入邮箱的动态密码
三、E426: 包已存在
验证包是否存在: https://registry.npmjs.org/ xxx