Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom new lines with Gulp uglify and Concat

I am using Gulp and gulp uglify and concat to create production JS. How can I add new lines before license comments?

Example output

/*! Version 1 */
function Test1(){}/*! Version 2 */
function Test(){}

Desired output

/*! Version 1 */
function Test1(){}
/*! Version 2 */
function Test(){}

My code that wraps the gulp sequence

function gulpDeploy(src, fileName, dest){
    gulp.src(src)
        .pipe(concat(fileName, {
            newLine:'\n;'
        }))
        .pipe(uglify({
            preserveComments : 'license'
        }))
        .pipe(gulp.dest(dest));
}

It looks like the newLine option should do it, but it doesn't do anything..

like image 311
BarryBones41 Avatar asked Dec 01 '25 22:12

BarryBones41


1 Answers

I'd be very interested in seeing alternative answers that use just uglify and concat to do this, but a naive fix using gulp-replace would be this:

var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var replace = require('gulp-replace');

gulp.task('default', [], function() {
  gulp.src('file*.js')
    .pipe(concat('output.js', { newLine: '\n;' }))
    .pipe(uglify({ preserveComments: 'license' }))
    .pipe(replace(/(\/\*\! Version [^*]* \*\/)/g, '\n$1')) // Version-comments to new line
    .pipe(replace(/^\s*\r?\n/gm, '')) // Remove empty lines that may get left
    .pipe(gulp.dest('./build'));
});

I would've preferred to have the first regex find only Version-comments that don't already start on the start of a new line (so the second replace call wouldn't be needed), but it seemed quite hard to get that regex to work (for one because negative lookbehind doesn't seem to work, or I'd think you could use (?<!^)\/\*\! Version [^*]* \*\/ to do it...)

like image 198
Jeroen Avatar answered Dec 03 '25 12:12

Jeroen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!