mkdir vue-auto-router-cli
cd vue-auto-router-cli
npm init -y
安裝handlebars
npm install handlebars -S
打開(kāi)項(xiàng)目
創(chuàng)建基礎(chǔ)命令
新建bin/kkb
注冊(cè)解析器用node語(yǔ)言
選擇JavaScript react語(yǔ)言
#!/usr/bin/env node
const program = require('commander')//創(chuàng)建命令
program.version(require('../package').version)//定義版本號(hào)options
.command('init <name>','init project')//第一個(gè)參數(shù)是命令 第二個(gè)參數(shù)是說(shuō)明
.command('refresh','refresh routes...')
program.parse(process.argv)
package.json加上
"bin":{
"kkb":"./bin/kkb"
},
運(yùn)行npm link
敲命令kkb 就會(huì)執(zhí)行kkb的腳本
init命令
創(chuàng)建bin/kkb-init
寫kkb init name的實(shí)現(xiàn)
這里的操作主要是克隆github的一個(gè)工程
#!/usr/bin/env node
const program = require('commander')
const {clone} = require('../lib/download')
program.action(async name => {
console.log('創(chuàng)建項(xiàng)目:'+name)
await clone('github:su37josephxia/vue-template',name)
})
program.parse(process.argv)
添加權(quán)限
chmod +x bin/*
運(yùn)行命令
kkb init test
這時(shí)候工程里面會(huì)多出一個(gè)test的工程
進(jìn)入工程
cd test
安裝依賴
npm i
運(yùn)行
npm run serve
refresh命令
創(chuàng)建bin/kkb/refresh
讀取test/src/views里面的所有頁(yè)面 遍歷出一個(gè)對(duì)象的格式
{
hello:hello.vue
}
利用模板把對(duì)象編譯成router和App.vue里面的配置
#!/usr/bin/env node
const program = require('commander')
const symbols = require('log-symbols') //圖片庫(kù)
const chalk = require('chalk')//粉筆 變log顏色
// console.log(process.argv)
program.action(() => {
console.log('refresh .... ')
})
program.parse(process.argv)
const fs = require('fs')//文件讀取
const handlebars = require('handlebars')//模板渲染
//路徑從test文件夾開(kāi)始算
//讀views 排除home
const list = fs.readdirSync('./src/views')
.filter(v => v !== 'Home.vue')
.map(v => ({
//去掉后綴 轉(zhuǎn)小寫 onePage
name: v.replace('.vue', '').toLowerCase(),
//onePage.vue
file: v
}))
//調(diào)用
compile({
list
}, './src/router.js', './template/router.js.hbs')
//調(diào)用
compile({
list
}, './src/App.vue', './template/App.vue.hbs')
function compile(meta, filePath, templatePath) {
if (fs.existsSync(templatePath)) {
//讀取模板
const content = fs.readFileSync(templatePath).toString();
//渲染
const result = handlebars.compile(content)(meta);
//根據(jù)數(shù)據(jù)渲染模板
fs.writeFileSync(filePath, result);
}
//打印日志
console.log(symbols.success, chalk.green(`${filePath} 創(chuàng)建成功`))
}
發(fā)布
創(chuàng)建bin/publish.sh
#!/usr/bin/env bash
npm config get registry # 檢查倉(cāng)庫(kù)鏡像庫(kù)
npm config set registry=http://registry.npmjs.org
echo '請(qǐng)進(jìn)行登錄相關(guān)操作:'
npm login # 登陸
echo "-------publishing-------"
npm publish # 發(fā)布
npm config set registry=https://registry.npm.taobao.org # 設(shè)置為淘寶鏡像 echo "發(fā)布完成"
exit
控制臺(tái)添加權(quán)限
chmod +x publish.sh
運(yùn)行命令
./publish.sh
登錄