Skip to content

introduction

gulp is a builder for web packing that resembles make but for web pages. The most simple use case is combining a javascript project into one file so we can use it in a web project.

Gulp is completely asynchronous, the synchronous functions were removed in later versions because they caused errors.

Here is a small gulpfile.js to explain some concepts.

var concat = require('gulp-concat')
var uglify = require('gulp-uglify');
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');

var b = // does not work
gulp.task('build', function() {
    return gulp.src('./src/*.js')
        .pipe(sourcemaps.init())
            .pipe(concat('main.js'))
            .pipe(uglify())
        .pipe(sourcemaps.write('../maps'))
        .pipe(gulp.dest('./dist/'));
});
console.log(b) // undefined

gulp.task('watch', function(){ 
    //gulp.watch('**/*.scss', ['sass']);          
    gulp.watch('src/**/*.js', gulp.series('build')); 
});

// task 'default' is special, like main in C
gulp.task('default', gulp.series('build', 'watch'));

// run gulp --tasks for an overview

Gulp is just plain javascript, it can even be typescipt or other flavours if you name it gulpfile.ts etc.. First some plugin includes, these can be installed with npm.

But let's start from the end-up, because 'default' is the main entry of the gulpfile. So these commands do the same :

gulp 
gulp default

The main entry says 'the task default runs the tasks build and watch in sequence'

gulp.task('default', gulp.series('build', 'watch'));

Tasks build and watch are defined higher up, watch just looks at the files mentioned and runs the tasks specified if any of them change.

The task given can be a function variable , but also another series called by task name.

    // works 
    gulp.watch('src/**/*.js', gulp.series('build')); 
    // does not work !!
    gulp.watch('src/**/*.js', b);  

It combines a number of plugin functions to gather all js files in the src directory into the file dist/main.js.

  • take all js sources from ./src
  • concatenate them into main.js
  • uglify the file but calculate the source maps
  • put the sourcemap in ../maps/main.js.map
  • put main.js in dist.

dist/main.js will now end in

//# sourceMappingURL=../maps/main.js.map

This setup just concatenates all sources, but a webpack approach is also possible.

https://www.npmjs.com/package/webpack-stream