cssmin.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. 'use strict';
  2. var path = require('path');
  3. var util = require('util');
  4. var CleanCSS = require('clean-css');
  5. var chalk = require('chalk');
  6. var maxmin = require('maxmin');
  7. module.exports = function (grunt) {
  8. var getAvailableFiles = function (filesArray) {
  9. return filesArray.filter(function (filepath) {
  10. if (!grunt.file.exists(filepath)) {
  11. grunt.log.warn('Source file ' + chalk.cyan(filepath) + ' not found');
  12. return false;
  13. }
  14. return true;
  15. });
  16. };
  17. grunt.registerMultiTask('cssmin', 'Minify CSS', function () {
  18. var created = {
  19. maps: 0,
  20. files: 0
  21. };
  22. var size = {
  23. before: 0,
  24. after: 0
  25. };
  26. this.files.forEach(function (file) {
  27. var options = this.options({
  28. rebase: false,
  29. report: 'min',
  30. sourceMap: false
  31. });
  32. var availableFiles = getAvailableFiles(file.src);
  33. var compiled = '';
  34. options.rebaseTo = path.dirname(file.dest);
  35. try {
  36. compiled = new CleanCSS(options).minify(availableFiles);
  37. if (compiled.errors.length) {
  38. grunt.warn(compiled.errors.toString());
  39. return;
  40. }
  41. if (compiled.warnings.length) {
  42. grunt.log.error(compiled.warnings.toString());
  43. }
  44. if (options.debug) {
  45. grunt.log.writeln(util.format(compiled.stats));
  46. }
  47. } catch (err) {
  48. grunt.log.error(err);
  49. grunt.warn('CSS minification failed at ' + availableFiles + '.');
  50. }
  51. var compiledCssString = compiled.styles;
  52. var unCompiledCssString = availableFiles.map(function (file) {
  53. return grunt.file.read(file);
  54. }).join('');
  55. size.before += unCompiledCssString.length;
  56. if (options.sourceMap) {
  57. compiledCssString += '\n' + '/*# sourceMappingURL=' + path.basename(file.dest) + '.map */';
  58. grunt.file.write(file.dest + '.map', compiled.sourceMap.toString());
  59. created.maps++;
  60. grunt.verbose.writeln('File ' + chalk.cyan(file.dest + '.map') + ' created');
  61. }
  62. grunt.file.write(file.dest, compiledCssString);
  63. created.files++;
  64. size.after += compiledCssString.length;
  65. grunt.verbose.writeln('File ' + chalk.cyan(file.dest) + ' created ' + chalk.dim(maxmin(unCompiledCssString, compiledCssString, options.report === 'gzip')));
  66. }, this);
  67. if (created.maps > 0) {
  68. grunt.log.ok(created.maps + ' source' + grunt.util.pluralize(this.files.length, 'map/maps') + ' created.');
  69. }
  70. if (created.files > 0) {
  71. grunt.log.ok(created.files + ' ' + grunt.util.pluralize(this.files.length, 'file/files') + ' created. ' + chalk.dim(maxmin(size.before, size.after)));
  72. } else {
  73. grunt.log.warn('No files created.');
  74. }
  75. });
  76. };