在项目里打开终端,先把需要的依赖装上,后续可以直接调用。
yarn add -D chalk commander download fs-extra handlebars inquirer log-symbols ora update-notifier
注册指令
当我们要运行调试脚手架时,通常执行 node ./bin/index.js
命令,但我还是习惯使用注册对应的指令,像 vue init webpack demo
的 vue
就是脚手架指令,其他命令行也要由它开头。打开 package.json
文件,先注册下指令:
“main”: “./bin/index.js”,
“bin”: {
“js-plugin-cli”: “./bin/index.js”
},
main
中指向入口文件 bin/index.js
,而 bin
下的 js-plugin-cli
就是我们注册的指令,你可以设置你自己想要的名称(尽量简洁)。
万物皆-v
我们先编写基础代码,让 js-plugin-cli -v
这个命令能够在终端打印出来。
打开 bin/index.js
文件,编写以下代码 :
#!/usr/bin/env node
// 请求 commander 库
const program = require(‘commander’)
// 从 package.json 文件中请求 version 字段的值,-v和–version是参数
program.version(require(‘…/package.json’).version, ‘-v, --version’)
// 解析命令行参数
program.parse(process.argv)
其中 #!/usr/bin/env node
(固定第一行)必加,主要是让系统看到这一行的时候,会沿着对应路径查找 node 并执行。
调试阶段时,为了保证 js-plugin-cli
指令可用,我们需要在项目下执行 npm link
(不需要指令时用 npm unlink
断开),然后打开终端,输入以下命令并回车:
js-plugin-cli -v
此时,应该返回版本号 1.0.0
,如图:
接下来我们将开始写逻辑代码,为了维护方便,我们将在 lib
文件夹下分模块编写,然后在 bin/index.js
引用。
upgrade 检查更新
打开 lib/update.js
文件,编写以下代码 :
// 引用 update-notifier 库,用于检查更新
const updateNotifier = require(‘update-notifier’)
// 引用 chalk 库,用于控制台字符样式
const chalk = require(‘chalk’)
// 引入 package.json 文件,用于 update-notifier 库读取相关信息
const pkg = require(‘…/package.json’)
// updateNotifier 是 update-notifier 的方法,其他方法可到 npmjs 查看
const notifier = updateNotifier({
// 从 package.json 获取 name 和 version 进行查询
pkg,
// 设定检查更新周期,默认为 1000 * 60 * 60 * 24(1 天)
// 这里设定为 1000 毫秒(1秒)
updateCheckInterval: 1000,
})
function updateChk() {
// 当检测到版本时,notifier.update 会返回 Object
// 此时可以用 notifier.update.latest 获取最新版本号
if (notifier.update) {
console.log(New version available: ${chalk.cyan(notifier.update.latest)}, it's recommended that you update before using.
)
notifier.notify()
} else {
console.log(‘No new version is available.’)
}
}
// 将上面的 updateChk() 方法导出
module.exports = upda