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 91 92 93 94 95 96 97 98 99 100
|
'use strict';
var path = require('path');
var util = require('util');
var CleanCSS = require('clean-css');
var chalk = require('chalk');
/**
* Simple replacement for https://www.npmjs.com/package/maxmin
*/
function maxmin(max, min) {
return `${max} B -> ${min} B`;
}
module.exports = function (grunt) {
var getAvailableFiles = function (filesArray) {
return filesArray.filter(function (filepath) {
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file ' + chalk.cyan(filepath) + ' not found');
return false;
}
return true;
});
};
grunt.registerMultiTask('cssmin', 'Minify CSS', function () {
var created = {
maps: 0,
files: 0
};
var size = {
before: 0,
after: 0
};
this.files.forEach(function (file) {
var options = this.options({
rebase: false,
report: 'min',
sourceMap: false
});
var availableFiles = getAvailableFiles(file.src);
var compiled = '';
options.rebaseTo = path.dirname(file.dest);
try {
compiled = new CleanCSS(options).minify(availableFiles);
if (compiled.errors.length) {
grunt.warn(compiled.errors.toString());
return;
}
if (compiled.warnings.length) {
grunt.log.error(compiled.warnings.toString());
}
if (options.debug) {
grunt.log.writeln(util.format(compiled.stats));
}
} catch (err) {
grunt.log.error(err);
grunt.warn('CSS minification failed at ' + availableFiles + '.');
}
var compiledCssString = compiled.styles;
var unCompiledCssString = availableFiles.map(function (file) {
return grunt.file.read(file);
}).join('');
size.before += unCompiledCssString.length;
if (options.sourceMap) {
compiledCssString += '\n' + '/*# sourceMappingURL=' + path.basename(file.dest) + '.map */';
grunt.file.write(file.dest + '.map', compiled.sourceMap.toString());
created.maps++;
grunt.verbose.writeln('File ' + chalk.cyan(file.dest + '.map') + ' created');
}
grunt.file.write(file.dest, compiledCssString);
created.files++;
size.after += compiledCssString.length;
grunt.verbose.writeln('File ' + chalk.cyan(file.dest) + ' created ' + chalk.dim(maxmin(unCompiledCssString, compiledCssString, options.report === 'gzip')));
}, this);
if (created.maps > 0) {
grunt.log.ok(created.maps + ' source' + grunt.util.pluralize(this.files.length, 'map/maps') + ' created.');
}
if (created.files > 0) {
grunt.log.ok(created.files + ' ' + grunt.util.pluralize(this.files.length, 'file/files') + ' created. ' + chalk.dim(maxmin(size.before, size.after)));
} else {
grunt.log.warn('No files created.');
}
});
};
|