
根据模版生成文件
前端小菜-贺俊兰 2020-09-05 Node
# 介绍
在项目开发过程中,特别是后台管理的系统,基本上70%以上的界面都是大致一样的,所有为了提高效率,我在想能否自动生成一些页面成为了我一直在思考的一件事。 今天我正式动手开始实践我的这一想法,因为node我不是很熟悉,所有虽然功能实现了,但是还是可以做很多优化以及拓展(根据配置页面,自动配置一些属性来生成)。 目前就记录我的第一版自动生成的经历。
# 实践过程
- 第一步我们新建一个项目,然后新建一个create.js。生成文件的逻辑代码我是放在这里面的。
- 因为是根据模版来生成,所以在根目录下新建一个templete文件夹,这里面放具体的模版文件。
- 新建一个views的文件夹,这里放的是具体生成后的文件。
//模版文件格式为:文件名.tpl
//模版文件中的变量使用格式:${变量}
templete
...模版文件
文件名.tpl
views
...生成后的文件
create.js 逻辑代码
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
准备工作完成后就是具体的实现过程了。
- 首先就是我们要读取模版文件,获取模版文件的内容。
- 读取到模版文件后我们获取的其实是一个buffer,我们转成String形式的。然后写一个方法获取字符串中的变量,其实主要的难点是在这里,至少我是这么认为的。
/** * @param {obj} 接收{key:value}形式的参数,根据key替换字符串中对应的key * @return {type} 返回替换后的String */ String.prototype.formatString = function () { if (arguments.length == 0) return this; const obj = arguments[0]; let s = this; for (var key in obj) { s = s.replace(new RegExp("\\${" + key + "}", "g"), obj[key]); } return s; }
1
2
3
4
5
6
7
8
9
10
11
12
13- 当字符串中的变量都转换成对应的值后,我们就可以直接生成文件了。
# 完整的CODE
const fs = require('fs')
const path = require('path')
/* 当前工作目录 */
const dir = path.resolve(__dirname)
/**
* @param {dir} 接收多个文件目录名
* @return {type} 返回文件目录名所对应的地址
*/
function resolve(...dir) {
return path.resolve(...dir)
}
String.prototype.formatString = function () {
if (arguments.length == 0) return this;
const obj = arguments[0];
let s = this;
for (var key in obj) {
s = s.replace(new RegExp("\\${" + key + "}", "g"), obj[key]);
}
return s;
}
class readFiles {
constructor() {
this.projectDir = dir //项目目录
this.tplDir = resolve(dir, 'template') //模版目录
}
/* 任务开始 */
start() {
try {
/* 读取模版 */
const data = fs.readdirSync(this.tplDir)
/* 获取模版文件内容,并解析字段 */
this.getTplFiles(data)
} catch (error) {
console.log(error)
}
}
/* 获取模版文件内容,并解析字段 */
getTplFiles(data) {
/* tplObj存储文件名和文件内容,{key:value}形式 */
const tplObj = {}
data.forEach(item => {
const objKey = item.slice(0, -4)
const fsData = fs.readFileSync(resolve(this.tplDir, item)).toString()
tplObj[item.slice(0, -4)] = fsData.formatString({ testValue1: '我是', testValue2: '哈哈哈', title: '神仙' })
this.createFile(tplObj)
})
}
/* 创建文件 */
createFile(obj) {
/* 根据存储的文件名和内容动态生成文件 */
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const element = obj[key];
const fileDir = resolve(this.projectDir, 'views/' + key + '.vue')
fs.writeFileSync(fileDir, element)
}
}
}
}
let fileCreate = new readFiles
fileCreate.start()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72