-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
101 lines (78 loc) · 2.4 KB
/
index.js
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
/**
* html <template> content replacement
* @author ydr.me
* @create 2016-01-21 15:22
* @uodate 2018年08月07日14:14:05
*/
'use strict';
var array = require('blear.utils.array');
var object = require('blear.utils.object');
var typeis = require('blear.utils.typeis');
var pkg = require('./package.json');
var defaults = {
conditions: [{
tagName: 'template'
}, {
tagName: 'script',
type: /template/
}],
progress: 'post-html',
replacements: [{
reg: /\s{2,}/g,
replace: ' '
}, {
reg: /[\n\r\t]/g,
replace: ''
}]
};
module.exports = function (configs) {
configs = object.assign({}, defaults, configs);
var replace = function (content) {
array.each(configs.replacements, function (index, replacement) {
content = content.replace(replacement.reg, replacement.replace);
});
return content;
};
return function (options) {
if (options.progress !== configs.progress) {
return options;
}
var coolie = this;
array.each(configs.conditions, function (index, condition) {
options.code = coolie.matchHTML(options.code, {
tag: condition.tagName
}, function (node) {
if (!condition.type) {
condition.type = /.*/;
}
node.attrs = node.attrs || {};
var matched = !!node.attrs.type;
if (!matched) {
return node;
}
switch (typeis(condition.type)) {
case 'string':
matched = node.attrs.type === condition.type;
break;
case 'regexp':
matched = condition.type.test(node.attrs.type);
break;
case 'function':
matched = condition.type(node);
break;
default:
matched = false;
}
if (!matched) {
return node;
}
node.content = node.content || '';
node.content = replace(node.content);
return node;
});
});
return options;
};
};
module.exports.package = pkg;
module.exports.defaults = defaults;