Ebooks

Gulp minify tutorial

Gulp minify tutorial shows how to minify JS code with gulp-minify plugin.

Gulp

Gulp is a Node task runner. It is a streaming build system in front-end web development. It helps automate such tasks as copying files, minifying JavaScript code, or compiling TypeScript to JavaScript.

The gulp-minify plugin minifies JS files. The resulting files are lighter. The minified files have the -min.js extension.

Installing Gulp and gulp-minify

We initiate a Node.js project and install Gulp and gulp-minify plugin.

$ npm init -y 
$ npm i --global gulp-cli
$ npm i gulp --save-dev

We initiate a Node project and install Gulp and Gulp CLI.

$ npm i --save-dev gulp-minify

We install the gulp-minify plugin.

Gulp-minify example

The following example demonstrates the usage of gulp-minify. We have an HTML table which displays countries and their populations. There is a Sort button which sorts the second column containing the population values. The JS code that sorts the table is being minified with gulp-minify.

$ mkdir public/js -p
$ mkdir src/js -p
$ touch public/index.html gulpfile.js src/js/main.js

We create two directories and three empty files.

public/index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Countries</title>
</head>

<body>
    <table id="tbl">
        <tr>
            <th>Country</th>
            <th>Population</th>
        </tr>
        <tr>
            <td>Slovakia</td>
            <td>5429000</td>
        </tr>
        <tr>
            <td>Norway</td>
            <td>5271000</td>
        </tr>
        <tr>
            <td>Croatia</td>
            <td>4225000</td>
        </tr>
        <tr>
            <td>Russia</td>
            <td>143439000</td>
        </tr>
        <tr>
            <td>Mexico</td>
            <td>122273000</td>
        </tr>
        <tr>
            <td>Vietnam</td>
            <td>95261000</td>
        </tr>
        <tr>
            <td>Sweden</td>
            <td>9967000</td>
        </tr>
        <tr>
            <td>Iceland</td>
            <td>337600</td>
        </tr>
        <tr>
            <td>Israel</td>
            <td>8622000</td>
        </tr>
        <tr>
            <td>Hungary</td>
            <td>9830000</td>
        </tr>
        <tr>
            <td>Germany</td>
            <td>82175700</td>
        </tr>
        <tr>
            <td>Japan</td>
            <td>126650000</td>
        </tr>
    </table>

    <button id="mybtn">Sort</button>

    <script src="js/main-min.js"></script>

</body>

</html>

This is the index.html file. It loads the main-min.js file, which is the minified version of the JS main.js file.

src/js/main.js
let btn = document.getElementById('mybtn');

btn.addEventListener('click', sortTable);

function sortTable() {

    const tbl = document.getElementById("tbl").tBodies[0];

    let store = [];

    for (let i = 0, len = tbl.rows.length; i < len; i++) {

        let row = tbl.rows[i];
        let value = parseInt(row.cells[1].textContent || row.cells[1].innerText);

        if (!isNaN(value)) {
            store.push([value, row]);
        }
    }

    store.sort((x, y) => {
        return x[0] - y[0];
    });

    for (let i = 0, len = store.length; i < len; i++) {

        tbl.appendChild(store[i][1]);
    }

    store = null;
}

The code sorts the second column of the table.

gulpfile.js
const gulp = require("gulp");
const minify = require("gulp-minify");

gulp.task('minify', () => {
  return gulp.src('src/js/main.js', { allowEmpty: true }) 
    .pipe(minify({noSource: true}))
    .pipe(gulp.dest('public/js'))
})

gulp.task('default', gulp.series(['minify']));

This is the gulpfile.js that contains our Gulp tasks.

gulp.task('minify', () => {
    return gulp.src('src/js/main.js', { allowEmpty: true }) 
        .pipe(minify({noSource: true}))
        .pipe(gulp.dest('public/js'))
})

The gulp.task() creates a new task, which we call minify. The gulp.src() creates a stream for reading the main.js file. With pipe() we pass the streamed data to the minify() function. In the end, we pass the compiled data to the gulp.dest(), which in turn creates a stream for writing the data to the file system. The final file is copied into the public/js directory.

gulp.task('default', gulp.series(['minify']));

The default task is a task that is executed if no task name is specified with Gulp CLI. It runs the minify task.

$ gulp
[20:53:58] Using gulpfile ~\Documents\gulp\minify\gulpfile.js
[20:53:58] Starting 'default'...
[20:53:58] Starting 'minify'...
[20:53:58] Finished 'minify' after 66 ms
[20:53:58] Finished 'default' after 69 ms

We run the default task. The main-min.js file is generated.

In this tutorial we have used gulp-minify to minify JS code.

You might also be interested in the following related tutorials: Node Sass tutorial, Gulp Sass tutorial.