Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active August 29, 2015 13:57
Show Gist options
  • Save dfkaye/9714261 to your computer and use it in GitHub Desktop.
Save dfkaye/9714261 to your computer and use it in GitHub Desktop.
preserving /*** multiline string comments ***/ in uglify

/*** multiline strings ***/ with uglifyjs

Just started playing with this (22 MAR 2014) ~ there appear to be two ways to preserve /*** multiline string comments ***/ when using uglify.

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 /* or */ delimiters from the comment body, so you need to test the first and last 2 chars in the comment value. Here's the quick&dirty regex to test it:

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

Supposing we have a source.js file with a multiline string (this one uses 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)});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment