思路:
- 自定义几个模板,分别上传到github或者码云上
- 通过命令行选择创建项目时要使用的模板
- 拉下远程仓库中的模板
前期工作:
- 准备好模板代码,放在github或者码云上
- 注册npm账号
- 添加对应的账号信息到注册表
- coding
代码
- 新建一个文件夹 然后
npm inti
注册信息
PS D:\备份\cli-test> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (cli-test)
version: (1.0.0)
description: 脚手架test
entry point: (index.js)
test command:
git repository:
keywords: cici cli
author: cici
license: (ISC) MIT
About to write to D:\备份\cli-test\package.json:
{
"name": "cli-test",
"version": "1.0.0",
"description": "脚手架test",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"cici",
"cli"
],
"author": "cici",
"license": "MIT"
}
生成的package.json
结构如上
- 安装需要的依赖
npm i chalk co co-prompt commander inquirer ora --save
- 创建脚手架目录(手动添加)结构
>cli-test
|--bin
|--cli
|--commands
|--init.js
|--list.js
|--add.js
|--delete.js
|--package.json
|--README.md
- 修改
package.json
添加cli
入口指令 改后如下
- 在bin目录下新建 cli(没有后缀!!),代码如下
- commands目录下 init.js,代码如下
- commands目录下 add.js,代码如下
- commands目录下 delete.js,代码如下
以上是全部代码
测试及发布
- 开发时测试
node bin/cli list 查看所有可用的模版
node bin/cli init 把模版下载下来,作为初始项目进行开发
node bin/cli add 根据引导添加模板
node bin/cli delete 根据引导删除模板
- 本地测试 全局
init
npm link ///只能自己本地使用。
- 发布
npm publish ///将包发布到npm上,所有人都可以安装使用。
例子:
cli-test> $ npm publish
+ cli-test@1.1.0
安装
npm install -g cli-test
地址
源码地址:https://github.com/CiciIvory/cici-cli
npm包下载地址:https://www.npmjs.com/package/cici-cli
资料参考来源:https://segmentfault.com/a/1190000016996897
打包问题见下章,本篇篇幅过长