minify.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var _ = require('lodash'),
  3. fs = require('fs-extra'),
  4. uglify = require('uglify-js');
  5. var uglifyOptions = require('./uglify.options');
  6. /*----------------------------------------------------------------------------*/
  7. /**
  8. * Asynchronously minifies the file at `srcPath`, writes it to `destPath`, and
  9. * invokes `callback` upon completion. The callback is invoked with one argument:
  10. * (error).
  11. *
  12. * If unspecified, `destPath` is `srcPath` with an extension of `.min.js`.
  13. * (e.g. the `destPath` of `path/to/foo.js` would be `path/to/foo.min.js`)
  14. *
  15. * @param {string} srcPath The path of the file to minify.
  16. * @param {string} [destPath] The path to write the file to.
  17. * @param {Function} callback The function invoked upon completion.
  18. * @param {Object} [option] The UglifyJS options object.
  19. */
  20. function minify(srcPath, destPath, callback, options) {
  21. if (_.isFunction(destPath)) {
  22. if (_.isObject(callback)) {
  23. options = callback;
  24. }
  25. callback = destPath;
  26. destPath = undefined;
  27. }
  28. if (!destPath) {
  29. destPath = srcPath.replace(/(?=\.js$)/, '.min');
  30. }
  31. var output = uglify.minify(srcPath, _.defaults(options || {}, uglifyOptions));
  32. fs.writeFile(destPath, output.code, 'utf-8', callback);
  33. }
  34. module.exports = minify;