在项目开发中,使用 vue-cli 可快速进行创建项目,vue-cli 为我们提供了多种选项(router,eslint),便于我们在不同的项目中运用不同的配置。
在开发一些项目的同时,配置(eslint,tsconfig.json...)的复用率也很高,同时代码也应该可以进行复用。
这篇文章主要介绍如何使用 node 工具,和 templa-cli 这个库,快速的制作一个动态模板工具,那我们事不宜迟。
前言
这篇文章主要以实践为主,你可能还需要掌握以下知识。
制作模板
这里我们以一个 koa 项目模板为例子,目录结构为以下
- template
- routes
- app.js
- package.json
以 templa-cli 文档为例,文件假如要过滤,则使用 ^...$ 包含,里面使用 qs 的解析规则,文件内的内容使用 ejs 模板编译,后缀添加 .ejs
- template
- routes^includes=router$
- app.js.ejs
- package.json.ejs
// app.js.ejs
const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const consola = require('consola')
<% if (includes.includes('router')) { %>
const router require('./routes')
<% } -%>
// 创建 app 应用对象
const app = new Koa()
// 监听端口号, 启动服务器
app.listen(3001, () => consola.success('服务器启动成功, 地址: http://localhost:3001/'))
app
// 请求体参数处理
.use(bodyParser)
<% if (includes.includes('router')) { %>
// 路由请求
.use(router.routes())
// 路由错误处理
.use(router.allowedMethods())
<% } -%>
生成逻辑
有了模板之后,我们使用 templa-cli 提供的 API 方法,传入 options 与 includes 创建一个模板。
const { createTemplate } require('templa-cli')
createTemplate({
// 输入模板路径
input: 'template',
// 输出模板路径
output: 'out-template',
// 模板的配置,传入 name
options: {
name: "project name"
},
// 模板拥有什么功能
includes: ['router']
})
到这里,你就能看到 out-template 的模板是我们编译后的模板了。
编写命令
我们在继续编写 bin 中的脚本,这里会用到两个库
// package.json
{
"bin": {
"my-cli": "bin/index.js"
}
}
// bin/index.js
#!/usr/bin/env node
cosnt cac = require('cac')
const { Confirm } = require('enquirer')
const cli = cac('templa-cli')
// 注册 create 命令,接收一个项目名称值
cli.command('create <project-name>')
.action(async (name) => {
const includes = []
// 询问是否需要路由, 是则添加路由
const prompt = new Confirm({
name: 'router',
message: '是否创建路由?'
});
if (await prompt.run()) {
includes.push('router')
}
// 创建模板,到 name 中
createTemplate({
input: 'template',
output: name,
options: { name },
includes
})
})
总结
这里我们使用了 templa-cli 制作了一个简易的 cli 工具,可以足够应付一些简单的项目模板。
但实际上 vue-cli 并没有这么简单,他还包含了对依赖的版本管理,这做起来也会使得 cli 更加复杂。
其实命令行询问者不单单只有 enquirer 这个工具,市面上还有很多这类工具,例如 Inquirer、prompts,可以根据自己的情况而定。
最后,templa-cli 是一个简单的动态模板脚手架工具,如果觉得好用可以点个 star,成为支持我的动力!
blog:www.hairy.blog/ github:github.com/TuiMao233