index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. var path = require('path');
  3. var fs = require('graceful-fs');
  4. var gutil = require('gulp-util');
  5. var map = require('map-stream');
  6. var jsmin = require('jsmin-sourcemap');
  7. var filesize = require('filesize');
  8. var tempWrite = require('temp-write');
  9. module.exports = function () {
  10. return map(function (file, cb) {
  11. if (file.isNull()) {
  12. return cb(null, file);
  13. }
  14. if (file.isStream()) {
  15. return cb(new gutil.PluginError('gulp-jsmin', 'Streaming not supported'));
  16. }
  17. if (['.js'].indexOf(path.extname(file.path)) === -1) {
  18. gutil.log('gulp-jsmin: Skipping unsupported js' + gutil.colors.blue(file.relative));
  19. return cb(null, file);
  20. }
  21. tempWrite(file.contents, path.extname(file.path), function (err, tempFile) {
  22. if (err) {
  23. return cb(new gutil.PluginError('gulp-jsmin', err));
  24. }
  25. fs.stat(tempFile, function (err, stats) {
  26. if (err) {
  27. return cb(new gutil.PluginError('gulp-jsmin', err));
  28. }
  29. fs.readFile(tempFile, { encoding : 'UTF-8'}, function(err, data) {
  30. if (err) {
  31. return cb(new gutil.PluginError('gulp-jsmin', err));
  32. }
  33. var minimized = jsmin({'code': data, 'src': file.relative, 'dist':file.relative + '.min.js'});
  34. gutil.log('gulp-jsmin:', gutil.colors.green('✔ ') + file.relative);
  35. file.contents = new Buffer(minimized.code);
  36. file.sourceMap = JSON.parse(minimized.sourcemap);
  37. cb(null, file);
  38. });
  39. });
  40. });
  41. });
  42. };