如何建立屬於自己的腳手架
原理
我們每次搭建專案都需要建立專案,然後進行一系列的基礎配置,封裝基礎api ,配置webpack,浪費了很多時間和精力,用自己封裝的腳手架模板就可以每次像建立vue,react那樣一樣簡單,有能力的還可以去封裝自己的框架。
參考自beleve666大神的文章
原始碼檢視github
原理就:利用npm封裝外掛,拉取我們在github上託管的專案,拉取完畢後把依賴的.git .svn刪除掉 並用node.js更改json引數
1. 先上外掛依賴
inquirer:使用者與命令列互動的工具
ora:實現node.js 命令列環境的 loading效果, 和顯示各種狀態的圖示等
log-symbols:提供帶顏色的符號
Chalk:改變文字背景顏色
node-notifier:通知外掛
shelljs:可以呼叫命令列工具
2.先搭一個基礎npm包
npm包釋出教程 這裡就不多說了
3.先建立基礎命令
我們需要將我們的專案做下改動,首先在packge.json中新增如下內容:
"bin": { "template-ma": "index.js" },
"template-ma"是你自定義的命令,到這裡還不能使用,必須使用npm link
連結到全域性
4.建立入口檔案
Index.js檔案
#!/user/bin/env node
//你想要你的這個檔案中的程式碼用什麼可執行程式去執行它
//!/usr/bin/env node會去環境設定尋找node目錄
const commander = require('commander');//引入外掛
commander.command('init <name>') // 定義init子命令,<name>為必需引數可在action的function中接收,如需設定非必需引數,可使用中括號
.option('-d, --dev', '獲取開發版') // 配置引數,簡寫和全寫中使用,分割
.description('建立專案') // 命令描述說明
.action(function(name,option)){
console.log(name,option)
//這裡可以對引數進行操作
}
//這裡通過 command定義Init 子命令 當使用 init <name> 的時候 name 會在action中接收,
// option中 是傳遞配置引數,也在action中接收
//action接收一個回撥 action(function(name,option)){ 這裡可以對引數進行操作 }
//查詢版本號
commander.version(require('./package.json').version,'-v,-V,--version', '檢視版本號')
//這句話必須寫在最後面 提供幫助 -h
commander.parse(process.argv);
這裡可以執行一下
template-ma test -d
列印
test
true
5.建立執行函式
做一下拆分 把action函式提取到外部
//index.js
const initAction = require('./commands/init')
commander.command('init <name>') // 定義init子命令,<name>為必需引數可在action的function中接收,如需設定非必需引數,可使用中括號
.option('-d, --dev', '獲取開發版') // 配置引數,簡寫和全寫中使用,分割
.description('建立專案') // 命令描述說明
.action(initAction);
)
commands/init檔案
const initAction = async (name, option) => {
}
module.exports = initAction;
6.拉取模板
我們需要在github上託管自己的腳手架模板
然後 我們需要用download-git-repo拉取模板
和shelljs工具 進行條件判斷
// 檢查控制檯是否可以執行`git `,
if (!shell.which('git')) {
console.log(symbols.error, '對不起,git命令不可用!');
shell.exit(1);
}
// 驗證輸入name是否合法
if (fs.existsSync(name)) {
console.log(symbols.warning,`已存在專案資料夾${name}!`);
return;
}
if (name.match(/[^A-Za-z0-9\u4e00-\u9fa5_-]/g)) {
console.log(symbols.error, '專案名稱存在非法字元!');
return;
}
// 獲取option,確定模板型別(分支)
if (option.dev) branch = 'develop';
然後是拉取模板
function clone (remote, name, option) {
//三個引數,拉取的路徑,名字 ,分支
const downSpinner = ora('正在下載模板...').start();
//ora用於輸出loading
return new Promise((resolve, reject) => {
download(remote, name, option, err => {
if (err) {
downSpinner.fail();
console.log(symbols.error, chalk.red(err));
//chalk改變文字顏色
reject(err);
return;
};
downSpinner.succeed(chalk.green('模板下載成功!'));
resolve();
});
});
await clone(`direct:${remote}#${branch}`, name, { clone: true });
清理檔案
拉取下來後是和遠端倉庫關聯的,所以我們要把它們刪掉,還有清除一些多餘的檔案
const deleteDir = ['.git', '.gitignore', 'README.md', 'docs']; // 需要清理的檔案
const pwd = shell.pwd();
deleteDir.map(item => shell.rm('-rf', pwd + `/${name}/${item}`));
##根據使用者需求更改配置
這裡用到inquirer可以與命令列進行互動
我們可以設定幾個問題
const questions = [
{
type: 'input',
message: '請輸入模板名稱:',
name: 'name',
validate(val) {
if (!val) return '模板名稱不能為空!';
if (val.match(/[^A-Za-z0-9\u4e00-\u9fa5_-]/g)) return '模板名稱包含非法字元,請重新輸入';
return true;
}
},
{
type: 'input',
message: '請輸入模板關鍵詞(;分割):',
name: 'keywords'
},
{
type: 'input',
message: '請輸入模板簡介:',
name: 'description'
},
]
通過inquirer獲取到使用者輸入的內容
const answers = await inquirer.prompt(questions);
// 將使用者的配置列印,確認一下是否正確
console.log('------------------------');
console.log(answers);
let confirm = await inquirer.prompt([
{
type: 'confirm',
message: '確認建立?',
default: 'Y',
name: 'isConfirm'
}
]);
if (!confirm.isConfirm) return false;
我們拿到使用者輸入的值 就可以根據使用者的引數 進行更改
//簡單的讀取操作 就不過多描述了
let jsonData= fs.readFileSync((path.join(__dirname,'./'), 'malunan/package.json'),function(err,data){
console.log(err)
})
jsonData=JSON.parse(jsonData)
for(item in answers){
jsonData[item]=answers[item]
}
let obj=JSON.stringify(jsonData,null,'\t')
let sss=fs.writeFileSync((path.join(__dirname,'./'), 'malunan/package.json'),obj,function(err,data){
console.log(err,data)
})
這樣我們就根據使用者的引數,寫入到了package.json檔案 其他的用途 可自行開發
##自動安裝依賴
const installSpinner = ora('正在安裝依賴...').start();
if (shell.exec('npm install').code !== 0) {
console.log(symbols.warning, chalk.yellow('自動安裝失敗,請手動安裝!'));
installSpinner.fail(); // 安裝失敗
shell.exit(1);
}
installSpinner.succeed(chalk.green('依賴安裝成功!'));
//切入後臺的時候給使用者提示
notifier.notify({
title: 'YNCMS-template-cli',
icon: path.join(__dirname, 'coulson.png'),
message: ' ♪(^∀^●)ノ 恭喜,專案建立成功!'
});
// 自動開啟編輯器
if (shell.which('code')) shell.exec('code ./');
shell.exit(1);
這樣腳手架就搭建完畢了,可以在本地 template-ma init <name>
試一下效果
##原始碼
index.js
#!/usr/bin/env node
const commander = require('commander');
const initAction = require('./commands/init')
//查詢版本號
commander.version(require('./package.json').version,'-v,-V,--version', '檢視版本號')
commander.command('init <name>') // 定義init子命令,<name>為必需引數可在action的function中接收,如需設定非必需引數,可使用中括號
.option('-d, --dev', '獲取開發版') // 配置引數,簡寫和全寫中使用,分割
.description('建立專案') // 命令描述說明
.action(initAction);
//這句話必須寫在最後面 提供幫助 -h
commander.parse(process.argv);
clone.js
// utils/clone.js
const download = require('download-git-repo');
const symbols = require('log-symbols'); // 用於輸出圖示
const ora = require('ora'); // 用於輸出loading
const chalk = require('chalk'); // 用於改變文字顏色
module.exports = function (remote, name, option) {
const downSpinner = ora('正在下載模板...').start();
return new Promise((resolve, reject) => {
download(remote, name, option, err => {
if (err) {
downSpinner.fail();
console.log(symbols.error, chalk.red(err));
reject(err);
return;
};
downSpinner.succeed(chalk.green('模板下載成功!'));
resolve();
});
});
};
init.js
// commands/init.js
const shell = require('shelljs');
const symbols = require('log-symbols');
const clone = require('../utils/clone.js');
const remote = 'https://github.com/MaLunan/components.git';
const fs =require('fs')
const ora = require('ora'); // 用於輸出loading
const chalk = require('chalk'); // 用於改變文字顏色
const notifier =require('node-notifier')
const path = require('path')
let branch = 'master';
const initAction = async (name, option) => {
// 0. 檢查控制檯是否可以執行`git `,
if (!shell.which('git')) {
console.log(symbols.error, '對不起,git命令不可用!');
shell.exit(1);
}
// 1. 驗證輸入name是否合法
if (fs.existsSync(name)) {
console.log(symbols.warning,`已存在專案資料夾${name}!`);
return;
}
if (name.match(/[^A-Za-z0-9\u4e00-\u9fa5_-]/g)) {
console.log(symbols.error, '專案名稱存在非法字元!');
return;
}
// 2. 獲取option,確定模板型別(分支)
if (option.dev) branch = 'develop';
// 4. 下載模板
await clone(`direct:${remote}#${branch}`, name, { clone: true });
// 5. 清理檔案
const deleteDir = ['.git', '.gitignore', 'README.md', 'docs']; // 需要清理的檔案
const pwd = shell.pwd();
deleteDir.map(item => shell.rm('-rf', pwd + `/${name}/${item}`));
const inquirer = require('inquirer');
// 定義需要詢問的問題
const questions = [
{
type: 'input',
message: '請輸入模板名稱:',
name: 'name',
validate(val) {
if (!val) return '模板名稱不能為空!';
if (val.match(/[^A-Za-z0-9\u4e00-\u9fa5_-]/g)) return '模板名稱包含非法字元,請重新輸入';
return true;
}
},
{
type: 'input',
message: '請輸入模板關鍵詞(;分割):',
name: 'keywords'
},
{
type: 'input',
message: '請輸入模板簡介:',
name: 'description'
},
// {
// type: 'list',
// message: '請選擇模板型別:',
// choices: ['響應式', '桌面端', '移動端'],
// name: 'type'
// },
// {
// type: 'list',
// message: '請選擇模板分類:',
// choices: ['整站', '單頁', '專題'],
// name: 'category'
// },
// {
// type: 'input',
// message: '請輸入模板風格:',
// name: 'style'
// },
// {
// type: 'input',
// message: '請輸入模板色系:',
// name: 'color'
// },
{
type: 'input',
message: '請輸入您的名字:',
name: 'author'
}
];
// 通過inquirer獲取到使用者輸入的內容
const answers = await inquirer.prompt(questions);
// 將使用者的配置列印,確認一下是否正確
console.log('------------------------');
console.log(answers);
let confirm = await inquirer.prompt([
{
type: 'confirm',
message: '確認建立?',
default: 'Y',
name: 'isConfirm'
}
]);
if (!confirm.isConfirm) return false;
//根據使用者配置調整檔案
let jsonData= fs.readFileSync((path.join(__dirname,'./'), 'malunan/package.json'),function(err,data){
console.log(err)
})
jsonData=JSON.parse(jsonData)
for(item in answers){
jsonData[item]=answers[item]
}
console.log(jsonData)
console.log(path.join(__dirname,`${name}/`))
let obj=JSON.stringify(jsonData,null,'\t')
let sss=fs.writeFileSync((path.join(__dirname,'./'), 'malunan/package.json'),obj,function(err,data){
console.log(err,data)
})
//自動安裝依賴
const installSpinner = ora('正在安裝依賴...').start();
if (shell.exec('npm install').code !== 0) {
console.log(symbols.warning, chalk.yellow('自動安裝失敗,請手動安裝!'));
installSpinner.fail(); // 安裝失敗
shell.exit(1);
}
installSpinner.succeed(chalk.green('依賴安裝成功!'));
//切入後臺的時候給使用者提示
notifier.notify({
title: 'YNCMS-template-cli',
icon: path.join(__dirname, 'coulson.png'),
message: ' ♪(^∀^●)ノ 恭喜,專案建立成功!'
});
// 8. 開啟編輯器
if (shell.which('code')) shell.exec('code ./');
shell.exit(1);
};
module.exports = initAction;