-
Notifications
You must be signed in to change notification settings - Fork 322
/
build
375 lines (329 loc) · 13.9 KB
/
build
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
const fs = require('fs-extra'),
path = require('path'),
os = require('os'),
config = require('./config'),
getPathInfo = (strPath, debug) => {
const result = {
type: undefined, // 类型 'dir'|'file'
extension: undefined, // 扩展名 'undefined|空|xxx'
name: undefined, // 文件名 不包含扩展名部分
isExist: undefined // 是否存在
};
if(!strPath){
return result;
};
try {
let stat = fs.statSync(strPath);
//如果路径是一个目录,则返回目录信息
if (stat.isDirectory()) {
result.type = 'dir';
result.isExist = true;
let backPath = path.resolve(strPath, '../'), // 跳到路径上一级目录
dirName = strPath.replace(backPath, ''), // 去除上级目录路径
re = /[/]|[\\]/g;
result.name = dirName.replace(re, ''); // 去除处理路径后的/\符号
return result;
};
if (stat.isFile()) {
result.type = 'file';
result.isExist = true;
};
if (stat.isSymbolicLink()){
result.type = 'symlink';
result.isExist = true;
};
} catch (error) {
if (debug) {
console.log(`${strPath} 文件不存在, ${error}`);
};
};
result.extension = (() => {
let extName = path.extname(strPath);
return extName[0] === '.' ? extName.slice(1) : extName;
})();
result.name = path.basename(strPath, `.${result.extension}`);
return result;
};
class Build{
constructor(option){
const _ts = this;
_ts.tplPath = path.join('decode.wxml');
_ts.option = option;
_ts.line = _ts.option.debug ? `\r\n` : '';
if(option.debug){
_ts.outDir = path.join(os.homedir(),'desktop',_ts.option.debug ? 'test' : '','towxml');
}else{
_ts.outDir = path.join(__dirname,'dist');
};
_ts.tplDir = path.join(__dirname);
}
init(){
const _ts = this;
this.writeTpl();
// 清空输出目录
fs.emptyDirSync(_ts.outDir);
let paths = (()=>{
let result = [];
// 添加根目录文件
['config','decode','index','towxml'].forEach(item => {
let itemPaths = (()=>{
let arr = [];
['js','json','wxml','wxss'].forEach(ext => {
let itemPath = path.join(_ts.tplDir,`${item}.${ext}`),
itemPathInfo = getPathInfo(itemPath);
// 文件或目录存在,则添加至拷贝队列
if(itemPathInfo.type){
arr.push(itemPath);
};
});
return arr;
})();
itemPaths.forEach(item => {
result.push(item);
});
});
// 添加自定义组件文件
config.components.forEach(item => {
let itemPath = path.join(_ts.tplDir,item),
itemPathInfo = getPathInfo(itemPath);
if(itemPathInfo.type === 'dir'){
result.push(itemPath);
}else{
console.log(`自定义组件 ${itemPath} 目录不存在`);
};
});
// 添加样式目录
result.push(path.join(_ts.tplDir,'style'));
// 添加转换
result.push(path.join(_ts.tplDir,'parse'));
return result;
})(),
parseDir = path.join(_ts.tplDir,'parse'),
highlight = path.join(parseDir,'highlight'),
highlightLang = path.join(highlight,'languages',path.sep),
markdownPlugins = path.join(parseDir,'markdown','plugins',path.sep),
allowFiles = (()=>{
let files = {};
config.highlight.forEach(item => {
let itemPath = path.join(highlightLang,`${item}.js`);
files[itemPath] = 1;
});
[...config.markdown,...config.components].forEach(item => {
let itemPath = path.join(markdownPlugins,`${item}.js`);
files[itemPath] = 1;
});
return files;
})();
// 复制相应的文件
paths.forEach(item => {
let dist = item.replace(_ts.tplDir,_ts.outDir);
fs.copySync(item,dist,{
filter:function(src,dist){
// 如果highlight未启用则忽略该目录
if(config.highlight.length){
if(src.indexOf(highlightLang) === 0){
return allowFiles[src] === 1;
};
}else{
if(path.join(src,path.sep).indexOf(highlight) === 0){
return false;
};
};
// 如果markdown扩展全部禁用则忽略所有插件
if(config.markdown.length){
if(src.indexOf(markdownPlugins) === 0){
return allowFiles[src] === 1;
};
}else{
if(path.join(src,path.sep).indexOf(markdownPlugins) === 0){
return false;
};
};
let srcInfo = getPathInfo(src);
return srcInfo.isExist && srcInfo.name[0] !== '.';
}
});
});
// highlight扩展开关处理
let markdownIndex = path.join(_ts.outDir,'parse','markdown','index.js');
let markdownIndexStr;
if(!config.highlight.length){
markdownIndexStr = fs.readFileSync(markdownIndex,'utf8');
markdownIndexStr = markdownIndexStr.replace(/hljs =/g,'\/\/ hljs =');
fs.writeFileSync(markdownIndex,markdownIndexStr);
};
// 处理微信新版本不能动态require的问题(parse/markdown/index.js)
const regMarkdownPluginsStr = (()=>{
let result = ``;
[...config.markdown,...config.components].forEach(item => {
if(!/^audio-player|table|todogroup|img$/.test(item)){
result += `md.use(require('./plugins/${item}'));`
};
});
return result;
})();
if(regMarkdownPluginsStr !== ''){
markdownIndexStr = fs.readFileSync(markdownIndex,'utf8');
markdownIndexStr = markdownIndexStr.replace(/\/\/@regMarkdownPlugins/g,regMarkdownPluginsStr);
fs.writeFileSync(markdownIndex,markdownIndexStr);
};
// 处理微信新版本不能动态require的问题(parse/highlight/index.js)
let highlightIndex = path.join(_ts.outDir,'parse','highlight','index.js');
let highlightIndexStr;
let registerLanguageStr = (()=>{
let result = ``;
config.highlight.forEach(item => {
result += `hljs.registerLanguage('${item}', require('./languages/${item}').default);`;
});
return result;
})();
if(registerLanguageStr){
highlightIndexStr = fs.readFileSync(highlightIndex,'utf8');
highlightIndexStr = highlightIndexStr.replace(/\/\/@registerLanguage/g,registerLanguageStr);
fs.writeFileSync(highlightIndex,highlightIndexStr);
};
// 创建自定义组件配置
let obj = {component:true,usingComponents:{decode:`/towxml/decode`}};
config.components.forEach(item => {
obj.usingComponents[item] = `/towxml/${item}/${item}`
});
fs.writeFileSync(path.join(_ts.outDir,'decode.json'),JSON.stringify(obj,null,2));
// 如果不启用highlight组件,则注释掉对应的样式
if(!config.highlight.length){
let styles = (()=>{
let files = ['dark.wxss','light.wxss'];
files.forEach((item,index) => {
files[index] = path.join(_ts.outDir,'style','theme',item);
});
return files;
})();
styles.forEach(item => {
let re = /@import .*highlight\/style\/.*;/g,
itemStr = fs.readFileSync(item,'utf8');
itemStr = itemStr.replace(re,'');
fs.writeFileSync(item,itemStr);
});
};
console.log(`构建完成,请将『`,_ts.outDir,`』目录复制到小程序项目目录下${!_ts.option.debug ? ',并改名为『towxml』' : ''}`);
}
// 输出模版
writeTpl(){
const _ts = this,
components = (()=>{
let str = ``;
[...config.wxml,...config.components].forEach(item => {
str += _ts.getComponent(item);
});
return str;
})(),
str = `<block wx:for="{{nodes.children}}" wx:for-index="i" wx:for-item="item" wx:key="i">${_ts.line}${_ts.tab(1)}<block wx:if="{{item.tag===undefined}}">{{item.text}}</block>${_ts.line}${components}</block>`;
fs.writeFileSync(_ts.tplPath,str);
}
// 获取渲染模版
getComponent(tag){
const _ts = this;
let attrs = _ts.getAttr(tag),
obj = (()=>{
let result = {};
config.components.forEach(item => {
result[item] = `${_ts.tab(1)}<block wx:if="{{item.tag==='${tag}'}}">${_ts.line}${_ts.tab(2)}<${item} data="{{item}}" ${attrs}/>${_ts.line}${_ts.tab(1)}</block>${_ts.line}`;
});
return result;
})();
if(tag && obj[tag]){
return obj[tag];
}else if(tag){
if(tag === 'view'){
return `${_ts.tab(1)}<block wx:if="{{item.tag==='${tag}'}}">${_ts.line}${_ts.tab(2)}<block wx:if="{{item.rely}}">${_ts.line}${_ts.tab(3)}<${tag} ${attrs}>${_ts.line}${_ts.tab(4)}<decode wx:if="{{item.children}}" nodes="{{item}}"/>${_ts.line}${_ts.tab(3)}</${tag}>${_ts.line}${_ts.tab(2)}</block>${_ts.line}${_ts.tab(2)}<block wx:else>${_ts.line}${_ts.tab(3)}<view class="h2w__${tag}Parent">${_ts.line}${_ts.tab(4)}<${tag} ${attrs}>${_ts.line}${_ts.tab(5)}<decode wx:if="{{item.children}}" nodes="{{item}}"/>${_ts.line}${_ts.tab(4)}</${tag}>${_ts.line}${_ts.tab(3)}</view>${_ts.line}${_ts.tab(2)}</block>${_ts.line}${_ts.tab(1)}</block>${_ts.line}`;
};
return `${_ts.tab(1)}<block wx:if="{{item.tag==='${tag}'}}">${_ts.line}${_ts.tab(2)}<view class="h2w__${tag}Parent">${_ts.line}${_ts.tab(3)}<${tag} ${attrs}>${_ts.line}${_ts.tab(4)}<decode wx:if="{{item.children}}" nodes="{{item}}"/>${_ts.line}${_ts.tab(3)}</${tag}>${_ts.line}${_ts.tab(2)}</view>${_ts.line}${_ts.tab(1)}</block>${_ts.line}`;
}else{
return `${_ts.tab(1)}<block wx:if="{{item.tag===undefined}}">{{item.text}}</block>${_ts.line}`;
};
}
// 判断是否为自定义组件
isComponents(tag){
for(let i=0,len=config.components.length; i<len; i++){
if(config.components[i] === tag){
return true;
}
};
return false;
}
// 获取标签所对应的属性
getAttr(tag){
const _ts = this;
let result = '',
obj = (()=>{
let result = {};
result['data-data'] = "{{item}}";
// 非自定义组件需要添加style、id、class相关属性
if(!_ts.isComponents(tag)){
config.attrs.forEach(item => {
result[item] = `{{item.attrs.${item}}}`
});
};
return result;
})(),
// 事件绑定方式
bindType = config.bindType;
// 添加事件属性
config.events.forEach(item => {
if(item === 'change'){
if(tag === 'checkbox-group'){
obj[`${bindType}:${item}`] = `_${item}`;
};
}else{
obj[`${bindType}:${item}`] = `_${item}`;
};
});
switch (tag) {
case 'video':
obj.poster="{{item.attrs.poster}}";
obj.src="{{item.attrs.src}}";
break;
case 'image':
obj.src="{{item.attrs.src}}";
obj.mode="{{item.attrs.mode ? item.attrs.mode : 'widthFix'}}";
obj['lazy-load']="{{item.attr['lazy-load']}}";
break;
case 'navigator':
obj.url="{{item.attrs.href}}";
break;
case 'checkbox-group':
obj.bindchange="{{item.attrs.bindchange}}";
break;
case 'checkbox':
obj.checked="{{item.attrs.checked}}";
obj.value="{{item.attrs.value}}";
break;
case 'radio':
obj.checked="{{item.attrs.checked}}";
break;
case 'rich-text':
delete obj.id;
obj.nodes="{{item.children}}";
// obj.space="nbsp"
break;
};
for(let key in obj){
result += `${key}="${obj[key]}" `;
};
result = result.substr(0,result.length-1);
return result;
}
// 得到tab缩进字符
tab(len){
let str = '',
option = this.option;
if(option.debug){
for(let i=0; i<len; i++){
str += '\t';
};
};
return str;
}
};
new Build({
debug:false
}).init();