公司的業(yè)務有部分需要兼容IE8,雖然公司內部已有相應的框架蔬胯,但是百度的San還是引起了個人的興趣对供,奈何San這個東西,一年多了配套還有待完善笔宿,為了快速構建項目犁钟,自建一個簡單cli棱诱,步驟如下:
創(chuàng)建cli項目
創(chuàng)建san-cli目錄泼橘,并使用npm init
創(chuàng)建package.json文件:
mkdir san-cli && cd san-cli
npm init
在交互詢問中輸入相應參數(shù),其中name參數(shù)檢驗npm中是否已占用迈勋,如創(chuàng)建好的package.json文件如下炬灭,其中bin
為cli調用的命令名稱,main
為入口js:
{
"name": "my-san-cli",
"version": "0.0.1",
"description": "Auto generate san(a MVVM framework) project template",
"main": "index.js",
"bin": {
"san": "./index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/woodstream/san-cli.git"
},
"keywords": [
"san-cli"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "woodstream",
"license": "MIT",
"bugs": {
"url": "https://github.com/woodstream/san-cli/issues"
},
"dependencies": {
}
}
由于入口為index.js靡菇,所以創(chuàng)建index.js文件重归,并寫入如下內容:
#!/usr/bin/env node
const clone = require('git-clone')
const program = require('commander')
const shell = require('shelljs');
const log = require('tracer').colorConsole()
program
.version('0.0.1')
.description('San(MVVM framework)應用模板工程的cli')
program
.command('* init <project> <tpl>')
.action(function(tpl, project) {
log.info('目前san-cli支持amd和webpack兩種模板,示例:san init myproject --amd | --webpack')
if (tpl && project) {
let pwd = shell.pwd()
let url;
if(tpl == '--amd'){
url = `https://github.com/woodstream/san-mui-with-amd.git`;
}else{
url = `https://github.com/woodstream/san-mui-with-webpack.git`;
}
log.info(`正在${url}拉取模板代碼 ...`)
clone(url, pwd + `/${project}`, null, function() {
shell.rm('-rf', pwd + `/${project}/.git`)
log.info('模板工程建立完成')
})
} else {
log.error('正確命令例子:san-cli init myproject --amd')
}
})
program.parse(process.argv)
意思是根據(jù)不同的命令參數(shù)厦凤,拉取不同多腳手架模版鼻吮,可以觀察到require到依賴模塊,所以npm里添加依賴配置较鼓,執(zhí)行命令:
npm i commander --save
npm i git-clone --save
npm i shelljs --save
npm i tracer --save
執(zhí)行完后再次打開package.json椎木,可以發(fā)現(xiàn)里面多了如下內容:
"dependencies": {
"commander": "^2.12.2",
"git-clone": "^0.1.0",
"shelljs": "^0.7.8",
"tracer": "^0.8.11"
}
安裝并測試cli
執(zhí)行如下命令全局安裝即可,:
npm i 上述san-cli項目的本地或遠程路徑 -g
安裝完成,測試:
san init san-demo --amd
發(fā)布到npm
1博烂、先到npm網(wǎng)站注冊一個賬號香椎,去關聯(lián)郵箱收取郵件并驗證郵箱。
2禽篱、在命令行登錄npm畜伐,輸入下述命令,隨后填入注冊時的信息:
npm adduser
3躺率、發(fā)布提交:
npm publish
4玛界、若發(fā)布失敗,檢查是否使用npm的源悼吱,如使用cnpm等第三方源的切換回npm源慎框。