1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | module.exports = function(grunt) {
|
11 |
|
12 |
|
13 | var uglifyjs = require('uglify-js');
|
14 | var gzip = require('gzip-js');
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | grunt.registerMultiTask('min', 'Minify files with UglifyJS.', function() {
|
21 | var files = grunt.file.expandFiles(this.file.src);
|
22 |
|
23 |
|
24 | var banner = grunt.task.directive(files[0], function() { return null; });
|
25 | if (banner === null) {
|
26 | banner = '';
|
27 | } else {
|
28 | files.shift();
|
29 | }
|
30 |
|
31 |
|
32 | var max = grunt.helper('concat', files, {separator: this.data.separator});
|
33 |
|
34 |
|
35 | var min = banner + grunt.helper('uglify', max, grunt.config('uglify'));
|
36 | grunt.file.write(this.file.dest, min);
|
37 |
|
38 |
|
39 | if (this.errorCount) { return false; }
|
40 |
|
41 |
|
42 | grunt.log.writeln('File "' + this.file.dest + '" created.');
|
43 |
|
44 | grunt.helper('min_max_info', min, max);
|
45 | });
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | grunt.registerHelper('uglify', function(src, options) {
|
54 | if (!options) { options = {}; }
|
55 | var jsp = uglifyjs.parser;
|
56 | var pro = uglifyjs.uglify;
|
57 | var ast, pos;
|
58 | var msg = 'Minifying with UglifyJS...';
|
59 | grunt.verbose.write(msg);
|
60 | try {
|
61 | ast = jsp.parse(src);
|
62 | ast = pro.ast_mangle(ast, options.mangle || {});
|
63 | ast = pro.ast_squeeze(ast, options.squeeze || {});
|
64 | src = pro.gen_code(ast, options.codegen || {});
|
65 |
|
66 | grunt.verbose.ok();
|
67 |
|
68 |
|
69 |
|
70 | return src + ';';
|
71 | } catch(e) {
|
72 |
|
73 | grunt.verbose.or.write(msg);
|
74 | pos = '['.red + ('L' + e.line).yellow + ':'.red + ('C' + e.col).yellow + ']'.red;
|
75 | grunt.log.error().writeln(pos + ' ' + (e.message + ' (position: ' + e.pos + ')').yellow);
|
76 | grunt.warn('UglifyJS found errors.', 10);
|
77 | }
|
78 | });
|
79 |
|
80 |
|
81 | grunt.registerHelper('gzip', function(src) {
|
82 | return src ? gzip.zip(src, {}) : '';
|
83 | });
|
84 |
|
85 |
|
86 | grunt.registerHelper('min_max_info', function(min, max) {
|
87 | var gzipSize = String(grunt.helper('gzip', min).length);
|
88 | grunt.log.writeln('Uncompressed size: ' + String(max.length).green + ' bytes.');
|
89 | grunt.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + String(min.length).green + ' bytes minified).');
|
90 | });
|
91 |
|
92 | };
|