Preserving /*** multiline strings ***/ with UglifyJS2

Here are two quick and dirty examples showing how to preserve /*** multiline string comments ***/ when using uglifyjs (i.e., uglify 2.0). The first uses the basic uglify cli approach, the second uses gulp.

Just started playing with this (22 MAR 2014) ~ haven't done a grunt or cha example yet ~ some day, maybe…

node cli example

see https://github.com/mishoo/UglifyJS2#keeping-comments-in-the-output

When uglify identifies a multiline comment in the output, it excludes the /* and */ delimiters from the comment body, so you need to test the first and last 2 characters.

Here's a quick&dirty regex for that:

if (/^\*\*/.test(comment.value) && /\*\*$/.test(comment.value)) {
    return true;
}

Supposing we have a source.js file with a multiline string (this one uses mstring where.js) syntax):

where(function() {
  /***
    input | output
    this  | this

  ***/
  expect(input).toBe(output);
});

Make a file like uglify-source.js

var UglifyJS = require("uglify-js");
var files = ['source.js']; // <= could do this cli-wise with process.argv
var fs = require('fs');

var all = [];

files.forEach(function(file){

  var result = UglifyJS.minify(file, {
    output: {
      comments: function (node, comment) {

        console.log(comment.value);
        if (/^\*\*/.test(comment.value) && /\*\*$/.test(comment.value)) {

          console.log('found tri-star comment')
          return true;
        }
      }
    }
  });

  all.push(result.code);
});

fs.writeFile('uglify-build.js', all.join('\n'));

Test it with

node uglify-source.js

Should have a new file uglify-build.js with preserved comments

where(function(){/***
    input | output
    this  | this

  ***/
expect(input).toBe(output)});

gulp example ~ with gulp-uglify and gulp-rename

see http://truongtx.me/2014/03/14/automate-javascript-development-with-gulp/

Use the same source.js

Make gulpfile.js

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

gulp.task('uglify', function(){
  gulp.src(['./source.js']) // could do this cli-wise with process.argv
  .pipe(uglify({

    preserveComments: function (node, comment) {

      console.log(comment.value);
      if (/^\*\*/.test(comment.value) && /\*\*$/.test(comment.value)) {

        console.log('found tri-star comment');
        return true;
      }
    }
  }))
  .pipe(rename('gulp-build.js'))
  .pipe(gulp.dest('./'));
});

Test it with

gulp uglify

Should have a new file gulp-build.js with preserved comments

where(function(){/***
    input | output
    this  | this

  ***/
expect(input).toBe(output)});