forked from hefangshi/fis-postpackager-simple
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
349 lines (334 loc) · 10.9 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
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
/*
* fis
* http://fis.baidu.com/
*/
'use strict';
var combineCount = 0;
var combineCache = {};
var stable = require("stable");
var defaultSetting = {
autoCombine : true,
fullPackHit : {
js : false,
css : false
}
};
/**
* 获取html页面中的<script ... src="path"></script> 资源
* 获取html页面中的<link ... rel="stylesheet" href="path" /> 资源
* 由于已经在标准流程之后,无需处理inline
* 不需要改动页面中内嵌的样式
* 需要将页面中内嵌的脚本移动到所有脚本的最下方
* 需要去除注释内的引用
* @param content
* @param pathMap
*/
function analyzeHtml(content, pathMap) {
var reg = /(<script(?:(?=\s)[\s\S]*?["'\s\w\/\-]>|>))([\s\S]*?)(?:<\/script\s*>)|<(link)\s+[\s\S]*?["'\s\w\/]>|<!--([\s\S]*?)-->/ig;
var single, result;
var resources = {
scripts: [],
inlineScripts: [],
styles: []
};
var replaced = content.replace(reg, function (m, $1, $2, $3, $4) {
//$1为script标签, $2为内嵌脚本内容, $3为link标签, $4为注释内容
if ($1) {
//如果标签设置了data-fixed则不会收集此资源
if (/(\sdata-fixed\s*=\s*)('true'|"true")/ig.test($1)) {
return m;
}
var head = /(\sdata-position\s*=\s*)('head'|"head")/ig.test($1);
if ($2) {
resources.inlineScripts.push({content: m, head: head });
} else {
result = m.match(/(?:\ssrc\s*=\s*)(?:'([^']+)'|"([^"]+)"|[^\s\/>]+)/i);
if (result && (result[1] || result[2])) {
var jsUrl = result[1] || result[2];
//不在资源表中的资源不处理
if (!pathMap[jsUrl]){
return m;
}
single = /(\sdata-single\s*=\s*)('true'|"true")/ig.test($1);
resources.scripts.push({
content: m,
id: pathMap[jsUrl],
single: single,
head: head
});
}
}
} else if ($3) {
var isCssLink = false;
result = m.match(/\srel\s*=\s*('[^']+'|"[^"]+"|[^\s\/>]+)/i);
if (result && result[1]) {
var rel = result[1].replace(/^['"]|['"]$/g, '').toLowerCase();
isCssLink = rel === 'stylesheet';
}
//对rel不是stylesheet的link不处理
if (!isCssLink){
return m;
}
//如果标签设置了data-fixed则不会收集此资源
if (/(\sdata-fixed\s*=\s*)('true'|"true")/ig.test(m)) {
return m;
}
result = m.match(/(?:\shref\s*=\s*)(?:'([^']+)'|"([^"]+)"|[^\s\/>]+)/i);
if (result && (result[1] || result[2])) {
var cssUrl = result[1] || result[2];
if (!pathMap[cssUrl]){
return m;
}
single = /(\sdata-single\s*=\s*)('true'|"true")/ig.test(m);
resources.styles.push({
content: m,
id: pathMap[cssUrl],
single: single
});
}
} else if ($4) {
//不处理注释
return m;
}
return '';
});
return {
resources: resources,
content: replaced
};
}
function getResourcePathMap(ret) {
var map = {};
fis.util.map(ret.map.res, function (subpath, file) {
map[file.uri] = subpath;
});
return map;
}
/**
* 将页面依赖的资源与打包资源对比合并
* @param resources
* @param ret
* @param fullPackHit 是否要求资源整体命中打包对象
* @returns {Array}
*/
function getPkgResource(resources, ret, fullPackHit) {
var pkgList = {};
var list = [];
var handled = {};
var idList = resources.map(function(resource){
return resource.id;
});
var resourceMap = {};
resources.forEach(function(resource){
resourceMap[resource.id] = resource;
});
function fullPackPass(resource){
if (!fullPackHit){
return true;
}
var pkg = ret.map.pkg[ret.map.res[resource.id].pkg];
var unHit = pkg.has.filter(function (id) {
return idList.indexOf(id) == -1;
});
return unHit.length === 0;
}
resources.forEach(function (resource) {
var id = resource.id;
if (handled[id]){
return false;
}
var res = ret.map.res[id];
handled[id] = true;
if (res.pkg && fullPackPass(resource)) {
var head = false;
ret.map.pkg[res.pkg].has.forEach(function(inPkg){
handled[inPkg] = true;
if (resourceMap[inPkg]){
head = head || (resourceMap[inPkg].head || false);
}
});
pkgList[res.pkg] = true;
list.push({
type: 'pkg',
id: res.pkg,
head: head
});
} else {
list.push({
type: 'res',
id: id,
single: resource.single,
head: resource.head
});
}
});
return list;
}
/**
* 自动打包零散资源
* @param resList
* @param ret
* @param settings
* @param conf
* @param opt
* @returns {Array}
*/
function autoCombine(resList, ret, conf, settings, opt) {
var list = [];
var toCombine = [];
var fileExt;
function getCombineHash(list){
var idList = list.map(function(res){
return res.id;
});
return stable(idList).join(',');
}
function flushCombine() {
if (toCombine.length == 1) {
//单独的文件不进行处理
list.push(toCombine[0]);
toCombine = [];
return;
}
if (toCombine.length !== 0) {
var hash = getCombineHash(toCombine);
var content = '';
var index = 0;
var has = [];
var id;
if (combineCache[hash]){
fis.log.debug('auto combine hit cache [' + hash + ']');
id = combineCache[hash];
}
else{
toCombine.forEach(function (res) {
var file = ret.ids[res.id];
var c = file.getContent();
has.push(file.getId());
if (!fileExt) {
fileExt = file.isJsLike ? 'js' : 'css';
}
if (c !== '') {
if (index++ > 0) {
content += '\n';
if (file.isJsLike) {
content += ';';
} else if (file.isCssLike) {
c = c.replace(/@charset\s+(?:'[^']*'|"[^"]*"|\S*);?/gi, '');
}
}
content += c;
}
});
var subpath = 'pkg/auto_combine_${index}'.replace('${index}', combineCount) + '.' + fileExt;
var file = fis.file(fis.project.getProjectPath(), subpath);
ret.pkg[file.subpath] = file;
file.setContent(content);
id = "auto_" + fileExt + "_" + combineCount;
ret.map.pkg[id] = {
uri: file.getUrl(opt.hash, opt.domain),
type: fileExt,
has: has
};
combineCache[hash] = id;
combineCount++;
}
list.push({
type: 'pkg',
id: id
});
toCombine = [];
}
}
resList.forEach(function (res) {
if (res.type === 'pkg') {
flushCombine();
list.push(res);
} else {
if (res.single) {
flushCombine();
list.push(res);
} else {
toCombine.push(res);
}
}
});
flushCombine();
return list;
}
function injectJs(jsList, content, ret) {
function getCharset() {
var charset = fis.config.get('project.charset');
switch (charset) {
case 'utf8':
return 'utf-8';
default:
return charset;
}
}
var scripts = '', headScripts = '';
jsList.forEach(function (js) {
var uri;
if (js.type === 'pkg') {
uri = ret.map.pkg[js.id].uri;
} else {
uri = ret.map.res[js.id].uri;
}
var script = '<script type="text/javascript" charset="' + getCharset() + '" src="' + uri + '"></script>\r\n';
if (js.head){
headScripts += script;
}else{
scripts += script;
}
});
return content.replace(/<\/body>/, scripts + '\n$&').replace(/<\/head>/, headScripts + '\n$&');
}
function injectCss(cssList, content, ret) {
var styles = '';
cssList.forEach(function (css) {
var uri;
if (css.type === 'pkg') {
uri = ret.map.pkg[css.id].uri;
} else {
uri = ret.map.res[css.id].uri;
}
styles += '<link type="text/css" rel="stylesheet" href="' + uri + '"/>\r\n';
});
return content.replace(/<\/head>/, styles + '\n$&');
}
function injectInlineJs(inlineScripts, content, ret) {
var inlines = '', headInlines = '';
inlineScripts.forEach(function (script) {
if (script.head){
headInlines += script.content;
}else{
inlines += script.content;
}
});
return content.replace(/<\/body>/, inlines + '\n$&').replace(/<\/head>/, headInlines + '\n$&');
}
module.exports = function (ret, conf, settings, opt) { //打包后处理
if (!opt.pack){
return;
}
combineCache = {};
combineCount = 0;
settings = fis.util.merge(fis.util.clone(defaultSetting), settings);
var pathMap = getResourcePathMap(ret);
fis.util.map(ret.src, function (subpath, file) {
if (file.isHtmlLike && file.noMapJs !== false) { //类html文件
var content = file.getContent();
var result = analyzeHtml(content, pathMap);
var jsList = getPkgResource(result.resources.scripts, ret, settings.fullPackHit.js);
var cssList = getPkgResource(result.resources.styles, ret, settings.fullPackHit.css);
if (settings.autoCombine !== false) {
jsList = autoCombine(jsList, ret, conf, settings, opt);
cssList = autoCombine(cssList, ret, conf, settings, opt);
}
content = injectJs(jsList, result.content, ret);
content = injectCss(cssList, content, ret);
content = injectInlineJs(result.resources.inlineScripts, content, ret);
file.setContent(content);
}
});
};