前言
其实在实际开发中,可能也会遇到,就是创建一个新的项目时。可能一些初始化,以及技术栈,和现有的项目的基本是一样的。所有这些频繁重复性的工作,或许可以做成一个脚手架类似于vue-cli。
制作流程
一项目初始化
1.新建一个项目 pro-init-cli,初始化项目npm init --y安装一些依赖commander,git-clone,
open,shelljs,如:
{
"name": "pro-init-cli",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
+ "commander": "^6.0.0",
+ "git-clone": "^0.1.0",
+ "shelljs": "^0.8.4"
}
}
- 新建
index.js文件编写测试代码,并且修改pack.json文件,全局link指令,如。
- index.js
+ #! /usr/bin/env node
+ console.log('测试')
- package.json,新增指令参数
+ "bin": {
+ "pro-init-cli": "./index.js"
+ },
- 全局link
npm link - 指令测试
实现pro-init-cli业务代码
#! /usr/bin/env node
+ const program = require('commander')
+ const shell = require('shelljs')
+ const download = require('git-clone')
+ const open = require('open')
+ // 定义版本
+ program.version('1.0.0')
+ // 定义命令
+ program
+ .command('new <name>')
+ .description('创建项目')
+ .action(name => {
+ const gitUrl = 'https://github.com/vuejs/vue-next-webpack-preview.git'
+ download(gitUrl, `./${name}`, () => {
+ // 删除 .git 隐藏文件
+ shell.rm('-rf', `${name}/.git`)
+ shell.cd(name)
+ shell.exec('npm install')
+ // 成功后的提示
+ console.log(`
+ 创建项目:${name} 成功
+ pro-init-cli run 启动项目
+ `)
+ })
+ })
+ program
+ .command('run')
+ .description('运行项目')
+ .action(() => {
+ // 使用 shell 完成
+ shell.exec('npm run dev')
+ console.log(`
+ 项目启动成功
+ `)
+ })
+ // 解析命令行参数
+ program.parse(process.argv)
测试如下
安装: npm insatll pro-init-cli -g