All Articles Kinsa Creative

Minify and Concatenate JavaScript with Gulp

Concatenate and minify JS with Gulp.

Building off the docs for gulp-concat, gulp-minify, and gulp-sourcemaps.

More on sourcemaps can be found in this Google article.

Install the Gulp CLI globally:

npm install gulp-cli -g

Intall Gulp-Minify, Gulp-Sourcemaps, and Gulp-Concat:

npm install gulp-minify gulp-sourcemaps gulp-concat --save-dev

Create a gulpfile in the root of the project:

touch gulpfile.js

Add to that:

'use strict';

const gulp = require('gulp');
const minify = require( 'gulp-minify' );
const concat = require( 'gulp-concat' );
const sourcemaps = require('gulp-sourcemaps');

function concatJS() {
    return gulp.src( [ './src/js/*.js' ] )
            // concat any JS files in `./src/js/` to a file called `all.js`
            .pipe( concat( 'all.js' ) )
            .pipe( sourcemaps.init() )
            // minify `all.js`; creates a file called `all-min.js` without further args specifying otherwise
            // this will tell it instead to make a file named `all.min.js`
            .pipe( minify( {
                        ext: '.min.js',
                        noSource: true
                    } ) 
            )
            // save the sourcemaps to a separate file (rather than adding the map to the minified JS file itself)
            .pipe( sourcemaps.write( './' ) )
            // save the concatenated, minified file to the `/dist` directory
            .pipe( gulp.dest( './dist' ) );
}

exports.concatJS = concatJS;

Run it:

gulp concatJS

Caveats

Minify is known to blow up when it encounters ES6 optional chaining, ?, as in document.querySelector( 'foo' )?.doSomethingWithFoo() which requires rewriting the optional using an if statement to check if foo exists before proceeding e.g.

const bar = document.querySelector( 'foo' );
if ( bar ) {
    bar.doSomethingWithFoo();
}

Feedback?

Email us at enquiries@kinsa.cc.