/blog/articles/

Force a concatenation order with gulp.js

A while back I made a screencast explaining my gulpfile.js. Since then my needs changed per project and recently I ran into a problem with my js task. The task should hint my manually edited scripts.js with JSHint, then concatenate that with jQuery and other third party scripts, run uglify and in the end save a scripts.min.js in a /dist folder. So far so good. Only problem was that the order in which the files got concatenated was totally random which is a problem because I needed jQuery at the top, then all the third party scripts and then my manually written code. Luckily there is a gulp plugin which can help us with that:

gulp-order You do everything like you did before but after you added all your sources you can reorder these and then keep doing whatever you want to do with the them. For me that looks like this:

gulp.task('js', function() {
    gulp.src('./js/scripts.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(addsrc('./js/_libs/*.js'))
        .pipe(order([
                'js/_libs/jquery-2.1.1.js',
                'js/_libs/jquery.bxslider.js',
                'js/_libs/jquery.form.js',
                'js/_libs/cf7.js',
                'js/scripts.js'
            ], { base: './' }))
        .pipe(concat('scripts.min.js'))
        .pipe(uglify({mangle: false}))
        .pipe(gulp.dest('./dist/js'));
});

I had to set the base option to './', which is the root of the project in order to make it work. This might not be necessary for you. Happy coding!

Martin Wolf

Hi, I’m Martin Wolf, a Freelance Frontend Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.