为什么要使用模板生成?
公司项目,有很多可复用的地方,比如新增一个单表的增删改查页面,这一次写完之后,可以将这个增删改查的代码和文件,抽象成一个通用的模板模型,下一次需要再用到的时候,只需要通过命令行工具自动把组件-通用样式-接口层定义生成出来就行了,大大的提升工作效率,增加摸鱼时间。
nodejs四件套
要想实现这样的小工具,必须熟练掌握nodejs四件套,就是以下四位。
path global fs-extra chalk
抽象模板模型(hbs文件)
假设我们的页面层,是由以下这种形式去组成的
- src -组件
- button
- index.tsx
- index.css
- Button.tsx
- radio
- checkbox .......
那么,我们就可以将此类的情况,抽象成一个通用的模板,形如:
接下来就是制作模板了,模板代码如下所示,通过传入的模板参数,动态生成的。
Component.tsx.hbs
index.tsx.hbs
index.css.hbs
生成脚本代码(gii)
const path = require('path');
const glob = require('glob');
const fs = require('fs-extra');
const chalk = require('chalk');
const { spawn } = require('child_process');
const handlebars = require('handlebars');
/**
* abc-xyz => AbcXyz
* @param {*} str
*/
const varCase = str => str.replace(/-[a-z]/g, m => m[1].toUpperCase()).replace(/^.{1}/, m => m.toUpperCase());
const lowCase = str => str.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`).replace(/^-/, '');
(async()=>{
//获取指令输入的第二个字符串
const command = process.argv[2]
console.log(chalk.green(`生成command:${command}`));
const dirName = lowCase(command);
const componentName = varCase(command);
console.log(chalk.green(`文件名是:${dirName}`));
console.log(chalk.green(`组件名是:${componentName}`));
spawn('mkdir', ['-p', path.join(process.cwd(), `src/${dirName}`)]);
//同步获取文件模板,这个方法吗,会返回一个文件流数组对象
tplFiles = glob.sync(path.join(__dirname,'template/*.hbs'))
tplFiles.forEach((async fileItem=>{
//将文件以UTF-8的形式获取
const content = await fs.readFile(fileItem,'utf-8')
//编译模板文件-获取内容
const tempalte = handlebars.compile(content);
const result = tempalte({
dirName,
componentName
})
//替换文件,和扩展名。
const newPath = fileItem.replace('scripts/template', `src/${dirName}`)
.replace('component', dirName)
.replace('Component', componentName)
.replace('.hbs', '');
await fs.writeFile(newPath, result);
console.log(chalk.green(`生成文件: ${newPath} 成功!`));
}))
})()
使用自定义的gii工具生成代码-示例
例如我执行node scripts/gii test
会在我的工程目录下生成代码文件,只需要根据你的业务改动一点代码就行了。
demo地址:gitee.com/lswstyle/gi…