| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | /* |
| 2 | * grunt-terser |
| 3 | * https://github.com/adascal/grunt-terser |
| 4 | * |
| 5 | * Copyright (c) 2018 Alexandr Dascal |
| 6 | * Licensed under the MIT license. |
| 7 | */ |
| 8 | |
| 9 | 'use strict'; |
| 10 | |
| 11 | var Terser = require('terser'); |
| 12 | |
| 13 | module.exports = function(grunt) { |
| 14 | // Please see the Grunt documentation for more information regarding task |
| 15 | // creation: http://gruntjs.com/creating-tasks |
| 16 | |
| 17 | grunt.registerMultiTask( |
| 18 | 'terser', |
| 19 | 'Grunt plugin for A JavaScript parser, mangler/compressor and beautifier toolkit for ES6+.', |
| 20 | function() { |
| 21 | // Merge task-specific and/or target-specific options with these defaults. |
| 22 | var options = this.options(); |
| 23 | var createdFiles = 0; |
| 24 | |
| 25 | // Iterate over all specified file groups. |
| 26 | this.files.forEach(function(f) { |
| 27 | // Concat specified files. |
| 28 | var src = f.src |
| 29 | .filter(function(filepath) { |
| 30 | // Warn on and remove invalid source files (if nonull was set). |
| 31 | if (!grunt.file.exists(filepath)) { |
| 32 | grunt.log.warn('Source file "' + filepath + '" not found.'); |
| 33 | return false; |
| 34 | } else { |
| 35 | return true; |
| 36 | } |
| 37 | }) |
| 38 | .reduce(function(sources, filepath) { |
| 39 | sources[filepath] = grunt.file.read(filepath); |
| 40 | |
| 41 | return sources; |
| 42 | }, {}); |
| 43 | |
| 44 | // Minify file code. |
| 45 | var result = Terser.minify(src, options); |
| 46 | |
| 47 | if (result.error) { |
| 48 | grunt.log.error(result.error); |
| 49 | return false; |
| 50 | } |
| 51 | |
| 52 | if (result.warnings) { |
| 53 | grunt.log.warn(result.warnings.join('\n')); |
| 54 | } |
| 55 | |
| 56 | // Write the destination file. |
| 57 | grunt.file.write(f.dest, result.code); |
| 58 | |
| 59 | if (options.sourceMap) { |
| 60 | var mapFileName = options.sourceMap.filename |
| 61 | ? options.sourceMap.filename |
| 62 | : f.dest + '.map'; |
| 63 | // Write the source map file. |
| 64 | grunt.file.write(mapFileName, result.map); |
| 65 | } |
| 66 | |
| 67 | // Print a success message for individual files only if grunt is run with --verbose flag |
| 68 | grunt.verbose.writeln('File "' + f.dest + '" created.'); |
| 69 | |
| 70 | // Increment created files counter |
| 71 | createdFiles++; |
| 72 | }); |
| 73 | |
| 74 | if (createdFiles > 0) { |
| 75 | grunt.log.ok( |
| 76 | `${createdFiles} grunt.util.pluralize(createdFiles, 'file/files') created.` |
| 77 | ); |
| 78 | } |
| 79 | } |
| 80 | ); |
| 81 | }; |