2
votes

I want to use gulp-useref to concatenate all of my JavaScript files into one.

Within my JavaScript files I have a mixture of pre-minified and non-minified files.

I would like to only uglify files which are not already minified (for build performance reasons) and https://github.com/jonkemp/gulp-useref#transform-streams suggests that this is possible (in fact, it looks easy). The following is my Gulp task definition:

gulp.task('compile', function () {
    return gulp.src('index.html')
        .pipe(useref({}, lazypipe().pipe(function() {
            return gulpif(['*.js', '!*.min.js'], uglify());
        })))
        .pipe(gulp.dest(paths.build));
});

This works, in that I get a concatenated file but the non-minified files remain unminified (pre-minified files are still minified -- as expected).

My code is partially based on this: https://github.com/craigjennings11/gulp-uglifyjs

Any idea why my files are not being minified?


References

3

3 Answers

2
votes

For anyone else encountering this problem: I found I had to use the **/ wildcard pattern once I started putting my globs inside an array in the condition parameter of the gulpif e.g.

gulp.task('compile', function () {
    return gulp.src('index.html')
        .pipe(useref({}, lazypipe().pipe(function() {
            return gulpif(['**/*.js', '!**/*.min.js'], uglify());
        })))
        .pipe(gulp.dest(paths.build));
});

Then it worked perfectly for me.

1
votes

The problem here is that useref is only passing through the concatinated file names, not the individual file names that get concatinated.

//in html
<!-- build:js assets/scripts/concat.js --> // <-- this one
<script src="assets/scripts/jquery.min.js"></script> // <-- not this one
<script src="assets/scripts/gsap.min.js"></script> // <-- not this one
<script src="assets/scripts/script1.js"></script> // <-- not this one
<script src="assets/scripts/script2.js"></script> // <-- not this one
<!-- endbuild -->

So what ever you pipe after will have to be applied to the entire concatinated file.

But with a little rearranging you could do something like this:

//in html
<!-- build:js assets/scripts/libs.js -->
<script src="assets/scripts/jquery.min.js"></script>
<script src="assets/scripts/gsap.min.js"></script>
<!-- endbuild -->

<!-- build:js assets/scripts/main.js -->
<script src="assets/scripts/script1.js"></script>
<script src="assets/scripts/script2.js"></script>
<!-- endbuild -->

That way you can use gulp-if to isolate main.js to uglify:

.pipe(gulpif('main.js', uglify()))
0
votes

Have you tried this?

gulp.task('compile', function () {
    return gulp.src('index.html')
        .pipe(useref())
        .pipe(gulpif(['*.js', '!*.min.js'], uglify()))
        .pipe(gulp.dest(paths.build));
});