背景需求:在日常开发中,随着项目越来越多,能重复利用的代码就越多,急需一套基本的模板来初始化项目,把代码放到自己的gitlab或github上,每次又得找到地址重新clone一下,很麻烦
期望的结果:XXX init 。。。一行命令解决
步骤:
1、申请一个npm账号,https://www.npmjs.com/
2、写一个npm项目
package.json:

    {  "name": "windssr",  "version": "1.0.8",  "description": "a tool service for react-ssr",  "main": "index.js",  "bin": {    "windssr": "index.js"  },  "author": "windseek",  "license": "ISC",  "dependencies": {    "chalk": "^2.4.2",    "co": "^4.6.0",    "co-prompt": "^1.0.0",    "commander": "^2.20.0"  },  "scripts": {    "test": "test"  },  "repository": {    "type": "git",    "url": "git+https://github.com/Windseek/react-ssr-cli.git"  },  "keywords": [    "react",    "react-ssr",    "wind-ssr",    "react-ssr-cli"  ],  "bugs": {    "url": "https://github.com/Windseek/react-ssr-cli/issues"  },  "homepage": "https://github.com/Windseek/react-ssr-cli#readme"}

init.js

'use strict'const exec = require('child_process').execconst co = require('co')const prompt = require('co-prompt')const config = require('./template.json')const chalk = require('chalk')module.exports = () => { co(function *() {    // 处理用户输入      let tplName = yield prompt('Template name (you can input one like react, vue, angular): ')      let projectName = yield prompt('Project name: ')      let gitUrl,branch;      console.log(config.tpl);    if (!config.tpl[tplName]) {        console.log(chalk.red('\n × Template does not support!'))        process.exit()    }    gitUrl = config.tpl[tplName].url    branch = config.tpl[tplName].branch    // git命令,远程拉取项目并自定义项目名    let cmdStr = `git clone ${gitUrl} ${projectName} && cd ${projectName} && git checkout ${branch}`    exec(cmdStr, (error, stdout, stderr) => {      if (error) {        console.log(error)        process.exit()      }      console.log(chalk.green('\n √ Generation completed!'))      console.log(`\n cd ${projectName} && npm install \n`)      process.exit()    })  })}

index.js

#!/usr/bin/env node --harmony'use strict'process.env.NODE_PATH = __dirname + '/../node_modules/'const program = require('commander')program    .version(require('./package').version)program    .usage('<command>')program    .command('init')    .description('Generate a new project')    .alias('i')    .action(() => {        require('./init.js')()    })program.parse(process.argv)

template.json:

{"tpl":{"react":{"url":"https://github.com/Windseek/reactssr.git","branch":"master"}}}

相关说明:
1、package.json里定义bin的位置
2、index里定义bin命令指定执行的代码
3、init里执行shell,去git上拿代码模板

安装和初始化:
1、npm install windssr -g
2、windssr init
3、选择要使用的模板,react,angular和vue

如果觉的对你有用的话,支持一下哈