vue-cli
, create-react-app
、react-native-cli
等都是很是优秀的脚手架,经过脚手架,咱们能够快速初始化一个项目,无需本身从零开始一步步配置,有效提高开发体验。尽管这些脚手架很是优秀,可是未必是符合咱们的实际应用的,咱们能够定制一个属于本身的脚手架(或公司通用脚手架),来提高本身的开发效率。javascript
脚手架的做用前端
本项目完整代码请戳: github.com/YvetteLau/B…vue
在开始以前,咱们须要明确本身的脚手架须要哪些功能。vue init template-name project-name
、create-react-app project-name
。咱们此次编写的脚手架(eos-cli)具有如下能力(脚手架的名字爱叫啥叫啥,我选用了Eos黎明女神):java
eos init template-name project-name
根据远程模板,初始化一个项目(远程模板可配置)eos config set <key> <value>
修改配置信息eos config get [<key>]
查看配置信息eos --version
查看当前版本号eos -h
你们能够自行扩展其它的 commander
,本篇文章旨在教你们如何实现一个脚手架。node
本项目完整代码请戳(建议先clone代码): github.com/YvetteLau/B…react
效果展现git
初始化一个项目github
修改.eosrc文件,从 vuejs-template 下载模板vue-cli
关于这些第三方库的说明,能够直接npm上查看相应的说明,此处不一一展开。shell
建立一个空项目(eos-cli),使用 npm init
进行初始化。
npm install babel-cli babel-env chalk commander download-git-repo ini inquirer log-symbols ora
复制代码
├── bin
│ └── www //可执行文件
├── dist
├── ... //生成文件
└── src
├── config.js //管理eos配置文件
├── index.js //主流程入口文件
├── init.js //init command
├── main.js //入口文件
└── utils
├── constants.js //定义常量
├── get.js //获取模板
└── rc.js //配置文件
├── .babelrc //babel配置文件
├── package.json
├── README.md
复制代码
开发使用了ES6语法,使用 babel
进行转义,
.bablerc
{
"presets": [
[
"env",
{
"targets": {
"node": "current"
}
}
]
]
}
复制代码
eos
命令node.js 内置了对命令行操做的支持,package.json
中的 bin
字段能够定义命令名和关联的执行文件。在 package.json
中添加 bin
字段
package.json
{
"name": "eos-cli",
"version": "1.0.0",
"description": "脚手架",
"main": "index.js",
"bin": {
"eos": "./bin/www"
},
"scripts": {
"compile": "babel src -d dist",
"watch": "npm run compile -- --watch"
}
}
复制代码
www 文件
行首加入一行 #!/usr/bin/env node
指定当前脚本由node.js进行解析
#! /usr/bin/env node
require('../dist/main.js');
复制代码
开发过程当中为了方便调试,在当前的 eos-cli
目录下执行 npm link
,将 eos
命令连接到全局环境。
npm run watch
复制代码
利用 commander
来处理命令行。
main
import program from 'commander';
import { VERSION } from './utils/constants';
import apply from './index';
import chalk from 'chalk';
/** * eos commands * - config * - init */
let actionMap = {
init: {
description: 'generate a new project from a template',
usages: [
'eos init templateName projectName'
]
},
config: {
alias: 'cfg',
description: 'config .eosrc',
usages: [
'eos config set <k> <v>',
'eos config get <k>',
'eos config remove <k>'
]
},
//other commands
}
// 添加 init / config 命令
Object.keys(actionMap).forEach((action) => {
program.command(action)
.description(actionMap[action].description)
.alias(actionMap[action].alias) //别名
.action(() => {
switch (action) {
case 'config':
//配置
apply(action, ...process.argv.slice(3));
break;
case 'init':
apply(action, ...process.argv.slice(3));
break;
default:
break;
}
});
});
function help() {
console.log('\r\nUsage:');
Object.keys(actionMap).forEach((action) => {
actionMap[action].usages.forEach(usage => {
console.log(' - ' + usage);
});
});
console.log('\r');
}
program.usage('<command> [options]');
// eos -h
program.on('-h', help);
program.on('--help', help);
// eos -V VERSION 为 package.json 中的版本号
program.version(VERSION, '-V --version').parse(process.argv);
// eos 不带参数时
if (!process.argv.slice(2).length) {
program.outputHelp(make_green);
}
function make_green(txt) {
return chalk.green(txt);
}
复制代码
download-git-repo
支持从 Github、Gitlab 下载远程仓库到本地。
get.js
import { getAll } from './rc';
import downloadGit from 'download-git-repo';
export const downloadLocal = async (templateName, projectName) => {
let config = await getAll();
let api = `${config.registry}/${templateName}`;
return new Promise((resolve, reject) => {
//projectName 为下载到的本地目录
downloadGit(api, projectName, (err) => {
if (err) {
reject(err);
}
resolve();
});
});
}
复制代码
init
命令在用户执行 init 命令后,向用户提出问题,接收用户的输入并做出相应的处理。命令行交互利用 inquirer
来实现:
inquirer.prompt([
{
name: 'description',
message: 'Please enter the project description: '
},
{
name: 'author',
message: 'Please enter the author name: '
}
]).then((answer) => {
//...
});
复制代码
在用户输入以后,开始下载模板,这时候使用 ora
来提示用户正在下载模板,下载结束以后,也给出提示。
import ora from 'ora';
let loading = ora('downloading template ...');
loading.start();
//download
loading.succeed(); //或 loading.fail();
复制代码
init.js
import { downloadLocal } from './utils/get';
import ora from 'ora';
import inquirer from 'inquirer';
import fs from 'fs';
import chalk from 'chalk';
import symbol from 'log-symbols';
let init = async (templateName, projectName) => {
//项目不存在
if (!fs.existsSync(projectName)) {
//命令行交互
inquirer.prompt([
{
name: 'description',
message: 'Please enter the project description: '
},
{
name: 'author',
message: 'Please enter the author name: '
}
]).then(async (answer) => {
//下载模板 选择模板
//经过配置文件,获取模板信息
let loading = ora('downloading template ...');
loading.start();
downloadLocal(templateName, projectName).then(() => {
loading.succeed();
const fileName = `${projectName}/package.json`;
if(fs.existsSync(fileName)){
const data = fs.readFileSync(fileName).toString();
let json = JSON.parse(data);
json.name = projectName;
json.author = answer.author;
json.description = answer.description;
//修改项目文件夹中 package.json 文件
fs.writeFileSync(fileName, JSON.stringify(json, null, '\t'), 'utf-8');
console.log(symbol.success, chalk.green('Project initialization finished!'));
}
}, () => {
loading.fail();
});
});
}else {
//项目已经存在
console.log(symbol.error, chalk.red('The project already exists'));
}
}
module.exports = init;
复制代码
config
配置eos config set registry vuejs-templates
复制代码
config 配置,支持咱们使用其它仓库的模板,例如,咱们可使用 vuejs-templates 中的仓库做为模板。这样有一个好处:更新模板无需从新发布脚手架,使用者无需从新安装,而且能够自由选择下载目标。
config.js
// 管理 .eosrc 文件 (当前用户目录下)
import { get, set, getAll, remove } from './utils/rc';
let config = async (action, key, value) => {
switch (action) {
case 'get':
if (key) {
let result = await get(key);
console.log(result);
} else {
let obj = await getAll();
Object.keys(obj).forEach(key => {
console.log(`${key}=${obj[key]}`);
})
}
break;
case 'set':
set(key, value);
break;
case 'remove':
remove(key);
break;
default:
break;
}
}
module.exports = config;
复制代码
rc.js
.eosrc 文件的增删改查
import { RC, DEFAULTS } from './constants';
import { decode, encode } from 'ini';
import { promisify } from 'util';
import chalk from 'chalk';
import fs from 'fs';
const exits = promisify(fs.exists);
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
//RC 是配置文件
//DEFAULTS 是默认的配置
export const get = async (key) => {
const exit = await exits(RC);
let opts;
if (exit) {
opts = await readFile(RC, 'utf8');
opts = decode(opts);
return opts[key];
}
return '';
}
export const getAll = async () => {
const exit = await exits(RC);
let opts;
if (exit) {
opts = await readFile(RC, 'utf8');
opts = decode(opts);
return opts;
}
return {};
}
export const set = async (key, value) => {
const exit = await exits(RC);
let opts;
if (exit) {
opts = await readFile(RC, 'utf8');
opts = decode(opts);
if(!key) {
console.log(chalk.red(chalk.bold('Error:')), chalk.red('key is required'));
return;
}
if(!value) {
console.log(chalk.red(chalk.bold('Error:')), chalk.red('value is required'));
return;
}
Object.assign(opts, { [key]: value });
} else {
opts = Object.assign(DEFAULTS, { [key]: value });
}
await writeFile(RC, encode(opts), 'utf8');
}
export const remove = async (key) => {
const exit = await exits(RC);
let opts;
if (exit) {
opts = await readFile(RC, 'utf8');
opts = decode(opts);
delete opts[key];
await writeFile(RC, encode(opts), 'utf8');
}
}
复制代码
npm publish
将本脚手架发布至npm上。其它用户能够经过 npm install eos-cli -g
全局安装。 便可使用 eos
命令。
本项目完整代码请戳: github.com/YvetteLau/B…
编写本文,虽然花费了必定时间,可是在这个过程当中,我也学习到了不少知识,谢谢各位小伙伴愿意花费宝贵的时间阅读本文,若是本文给了您一点帮助或者是启发,请不要吝啬你的赞和Star,您的确定是我前进的最大动力。 github.com/YvetteLau/B…
[1] npm依赖文档(www.npmjs.com/package/dow…)
增长参考文章:[简单搭建前端脚手架 ICE] (link.juejin.im/?target=htt…)