UNPKG

2.18 kBJavaScriptView Raw
1'use strict';
2var through = require('through2'),
3 uglify = require('uglify-js'),
4 merge = require('deepmerge'),
5 PluginError = require('gulp-util/lib/PluginError'),
6 applySourceMap = require('vinyl-sourcemaps-apply'),
7 reSourceMapComment = /\n\/\/# sourceMappingURL=.+?$/,
8 pluginName = 'gulp-uglify';
9
10function minify(file, options) {
11 var mangled;
12
13 try {
14 mangled = uglify.minify(String(file.contents), options);
15 mangled.code = new Buffer(mangled.code.replace(reSourceMapComment, ''));
16 return mangled;
17 } catch (e) {
18 return createError(file, e);
19 }
20}
21
22function setup(opts) {
23 var options = merge(opts || {}, {
24 fromString: true,
25 output: {}
26 });
27
28 if (options.preserveComments === 'all') {
29 options.output.comments = true;
30 } else if (options.preserveComments === 'some') {
31 // preserve comments with directives or that start with a bang (!)
32 options.output.comments = /^!|@preserve|@license|@cc_on/i;
33 } else if (typeof options.preserveComments === 'function') {
34 options.output.comments = options.preserveComments;
35 }
36
37 return options;
38}
39
40function createError(file, err) {
41 if (typeof err === 'string') {
42 return new PluginError(pluginName, file.path + ': ' + err, {
43 fileName: file.path,
44 showStack: false
45 });
46 }
47
48 var msg = err.message || err.msg || /* istanbul ignore next */ 'unspecified error';
49
50 return new PluginError(pluginName, file.path + ': ' + msg, {
51 fileName: file.path,
52 lineNumber: err.line,
53 stack: err.stack,
54 showStack: false
55 });
56}
57
58module.exports = function(opt) {
59
60 function uglify(file, encoding, callback) {
61 var options = setup(opt);
62
63 if (file.isNull()) {
64 return callback(null, file);
65 }
66
67 if (file.isStream()) {
68 return callback(createError(file, 'Streaming not supported'));
69 }
70
71 if (file.sourceMap) {
72 options.outSourceMap = file.relative;
73 options.inSourceMap = file.sourceMap.mappings !== '' ? file.sourceMap : undefined;
74 }
75
76 var mangled = minify(file, options);
77
78 if (mangled instanceof PluginError) {
79 return callback(mangled);
80 }
81
82 file.contents = mangled.code;
83
84 if (file.sourceMap) {
85 applySourceMap(file, mangled.map);
86 }
87
88 callback(null, file);
89 }
90
91 return through.obj(uglify);
92};