-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
90 lines (69 loc) · 2.2 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
/*
* fis
* http://fis.baidu.com/
*/
'use strict';
var UglifyJS = require('uglify-js');
var util = require('util');
var mergeMap = require('merge-source-map');
function uglify(content, file, conf) {
conf.fromString = true;
if (conf.sourceMap) {
var mapping = fis.file.wrap(file.dirname + '/' + file.filename + file.rExt + '.map');
conf.outSourceMap = mapping.subpath;
}
var ret = UglifyJS.minify(content, conf);
if (conf.sourceMap) {
var mapData = JSON.parse(ret.map);
mapData.sources = [file.subpath];
mapData.sourcesContent = [content];
var newData = {
version: mapData.version,
file: mapData.file,
sources: mapData.sources,
sourcesContent: mapData.sourcesContent,
names: mapData.names,
mappings: mapData.mappings
};
var originMapFile = popMapFile(file);
if (originMapFile) {
var merged = mergeMap(JSON.parse(originMapFile.getContent()), newData);
mapping.setContent(JSON.stringify(merged));
} else {
mapping.setContent(JSON.stringify(newData));
}
file.extras = file.extras || {};
file.extras.derived = file.extras.derived || [];
file.extras.derived.push(mapping);
// 先删掉原始的 sourceMappingURL
ret.code = ret.code.replace(/\n?\s*\/\/#\ssourceMappingURL=.*?(?:\n|$)/g, '');
ret.code += '\n//# sourceMappingURL=' + mapping.getUrl(fis.compile.settings.hash, fis.compile.settings.domain) + '\n';
}
return ret.code;
}
module.exports = function(content, file, conf){
try {
content = uglify(content, file, conf);
} catch (e) {
fis.log.warning(util.format('Got Error %s while uglify %s', e.message, file.subpath));
fis.log.debug(e.stack);
}
return content;
};
function popMapFile(file) {
var derived = file.derived;
var extraDerived = file.extras && file.extras.derived;
return popMapFromArray(derived) || popMapFromArray(extraDerived);
}
function popMapFromArray(derived) {
if (!Array.isArray(derived)) {
return null;
}
var index = derived.findIndex(function (ele) {
return ele.rExt === '.map';
});
if (index > -1) {
return derived.splice(index, 1)[0];
}
return null;
}