Appearance
开发扩展包
基础知识
有时我们需要创建自己的全局node命令,比如斑马兽开发的前端脚手架项目,就可以使用全局命令banmashou-vue
进行安装。
下面我们就来介绍 banmashou-vue
这个命令
初始项目
下面来创建项目并安装需要的扩展包
创建项目
首先创建项目
mkdir banmashou-vue
npm init -y
依赖包
然后安装依赖包
npm install chalk figlet inquirer nanospinner obtain-git-repo
依赖包说明
- chalk 命令行颜色
- figlet 显示文本图像
- inquirer 接收用户输入
- nanospinner 显示进度
- obtain-git-repo 下载git代码
- terminal-link 文本链接
package.json
下面是最终的package.json文件内容
- 添加
"type": "module"
即使用es6模块 - 选项
bin
用于定义命令名称与执行文件
{
"name": "banmashou-vue",
"description": "斑马兽前端脚手架",
"version": "1.0.1",
"license": "MIT",
"bin": {
"banmashou-vue": "index.js"
},
"author": {
"name": "何俊",
"email": "banmawang2021@163.com",
"url": "https://www.banmashou.com"
},
"type": "module",
"keywords": [
"banmashou-vue",
"何俊"
],
"files": [
"index.js",
"utils"
],
"scripts": {
"format": "prettier --write \"./**/*.{js,json}\""
},
"dependencies": {
"chalk": "^4.1.2",
"figlet": "^1.5.2",
"inquirer": "^9.0.0",
"nanospinner": "^1.1.0",
"obtain-git-repo": "^1.0.2"
},
"devDependencies": {
"prettier": "^2.7.1"
}
}
项目代码
下面我们来实现最终的命令代码
编写代码
创建 index.js
文件,用于项目代码的编写。
#!/usr/bin/env node
/**
* banmashou-vue
* 斑马兽前端脚手架
* @author 何俊 <https://www.banmashou.com>
*/
import chalk from 'chalk';
import inquirer from 'inquirer';
import fs from 'fs';
import { download } from 'obtain-git-repo';
import { createSpinner } from 'nanospinner';
import figlet from 'figlet';
figlet('banmashou.com', async function (err, data) {
//打印文字图案
console.log(data);
//可点击链接
console.log(
chalk.green(
`欢迎使用斑马兽前端脚手架`
)
);
//询问用户
const message = await inquirer.prompt({
name: 'dirname',
type: 'input',
message: '请输入目录名',
default() {
return 'banmashou-vue';
}
});
//目录是否已经存在
const dirIsExists = fs.existsSync(message.dirname);
if (dirIsExists) {
console.log(chalk.redBright('目录已经存在'));
} else {
//显示下载动画
const spinner = createSpinner('开始下载...').start();
//下载git代码
download(
'direct:https://gitee.com/banmawang/vue',
message.dirname,
{ clone: true },
function (err) {
if (err) {
spinner.error({ text: '下载失败' });
} else {
spinner.success({
text: '项目创建成功,请依次执行以下命令'
});
console.log(chalk.white(`cd ${message.dirname}`));
console.log(chalk.white('npm install'));
console.log(chalk.white('npm run dev'));
return;
}
}
);
}
});
测试执行
在项目中执行以下命令进行测试
node .
发布项目
下面我们来将扩展包提交到npmjs,供其他用户使用。
首次提交
你需要先在 https://www.npmjs.com/ 注册帐号
然后在命令行进行登录,如果你使用了 nrm
等命令切换过源,需要更改为npm 官方源
npm login
进入项目目录,并执行以下命令发布包
npm publish
然后登录 https://www.npmjs.com/ 就可以查看到包了
更新版本
修改扩展包代码后,需要修改package.json
中的version
后,再执行
npm publish
用户安装
其他用户要执行咱们的命令,首先需要全局安装
npm install -g banmashou-vue
然后就可以执行命令了
banmashou-vue