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