The answer from Wallace is great, but if the files you are trying to minify don't exist before grunt starts (i.e. if you are depending on another task), it won't work because the map is generated before any task is run.
I came up with a solution for minifying generated files individually, using the node package uglify-js instead of grunt-contrib-uglify.
- Add uglify-js to your package.json
- Add one of the following example to your Grunfile (just replace "YOUR FILES HERE" by the appropriate glob(s) if you are using Example 1).
- If you need to change the minified file destination or extension, use Example 2 instead. It uses grunt.file.recurse with a callback which provides you with the root directory, sub directory and file name of each file (it is easier then to build a custom destination path). Replace "FOLDER" by the directory you want to scan, and build your own "CUSTOM PATH HERE".
Example 1: With grunt.file.expand
grunt.registerTask('uglifyFiles', 'Uglifies files', function () {
var jsp = require("uglify-js").parser,
pro = require("uglify-js").uglify,
count = 0;
grunt.file.expand(['YOUR FILES HERE']).forEach(function (abspath) {
// Exclude already minified files (with extension .min.js)
if (!abspath.match(/\.min\.js$/i)) {
// Get Abstract Syntax Tree
var ast = jsp.parse(grunt.file.read(abspath));
// If mangling
// ast = pro.ast_mangle(ast);
// If squeezing
ast = pro.ast_squeeze(ast);
// Write new file
grunt.file.write(abspath.replace(/\.js$/i, '.min.js'), pro.gen_code(ast));
count += 1;
}
});
grunt.log.oklns("Successfully uglified " + count + " files");
});
Example 2: With grunt.file.recurse
grunt.registerTask('uglifyFiles', 'Uglifies files', function () {
var jsp = require("uglify-js").parser,
pro = require("uglify-js").uglify,
count = 0;
grunt.file.recurse('FOLDER', function callback(abspath, rootdir, subdir, filename) {
// Exclude already minified files (with extension .min.js)
if (!abspath.match(/\.min\.js$/i)) {
// Get Abstract Syntax Tree
var ast = jsp.parse(grunt.file.read(abspath));
// If mangling
// ast = pro.ast_mangle(ast);
// If squeezing
ast = pro.ast_squeeze(ast);
// Write new file, using abspath or rootdir, subdir and filename
grunt.file.write('CUSTOM PATH HERE', pro.gen_code(ast));
count += 1;
}
});
grunt.log.oklns("Successfully uglified " + count + " files");
});