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' ] )
            .pipe( sourcemaps.init() )
            // concat other JS files to a file called `all.js`
            .pipe( concat( 'all.js' ) )
            // minify `all.js`; creates a file called `all-min.js` without further args specifying otherwise
            .pipe( minify() )
            // save the sourcemaps to a separate file in the `/dist` directory (rather than adding them to the minified JS file itself)
            .pipe( sourcemaps.write( './dist' ) )
            // save the concatenated, minified file to the `/dist` directory
            .pipe( gulp.dest( './dist' ) );

exports.concatJS = concatJS;

Run it:

gulp concatJS


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 ) {


Email us at