背景需求:在平常開發中,隨着項目愈來愈多,能重複利用的代碼就越多,急需一套基本的模板來初始化項目,把代碼放到本身的gitlab或github上,每次又得找到地址從新clone一下,很麻煩
指望的結果:XXX init 。。。一行命令解決
步驟:
一、申請一個npm帳號,https://www.npmjs.com/
二、寫一個npm項目
package.json:vue
{ "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.jsnode
'use strict' const exec = require('child_process').exec const 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.jsreact
#!/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:git
{"tpl":{"react":{"url":"https://github.com/Windseek/reactssr.git","branch":"master"}}}
寫好了須要發佈一下嘍:
一、npm login,填寫用戶名,密碼
二、修改package.json裏version
三、npm publish
四、去https://www.npmjs.com/ 上看當作功沒有github
相關說明:
一、package.json裏定義bin的位置
二、index裏定義bin命令指定執行的代碼
三、init裏執行shell,去git上拿代碼模板shell
安裝和初始化:
一、npm install windssr -g
二、windssr init
三、選擇要使用的模板,react,angular和vuenpm
若是覺的對你有用的話,支持一下哈
json