Development is iterative, and the most important thing for developers is to quickly see their changes. However, in a production environment things like file size, number of files served, and other optimizations are incredibly important.

Gulp is great for build and deployment of your application, as well as automating your development workflow.

"use strict";

var gulp = require('gulp'),
  concat = require('gulp-concat'),
  uglify = require('gulp-uglify'),
  rename = require('gulp-rename'),
    sass = require('gulp-sass'),
    maps = require('gulp-sourcemaps'),
     del = require('del');

gulp.task("concatScripts", function() {
    return gulp.src([
        'js/jquery.js',
        'js/sticky/jquery.sticky.js',
        'js/main.js'
        ])
    .pipe(maps.init())
    .pipe(concat('app.js'))
    .pipe(maps.write('./'))
    .pipe(gulp.dest('js'));
});

gulp.task("minifyScripts", ["concatScripts"], function() {
  return gulp.src("js/app.js")
    .pipe(uglify())
    .pipe(rename('app.min.js'))
    .pipe(gulp.dest('js'));
});

gulp.task('compileSass', function() {
  return gulp.src("scss/application.scss")
      .pipe(maps.init())
      .pipe(sass())
      .pipe(maps.write('./'))
      .pipe(gulp.dest('css'));
});

gulp.task('watchFiles', function() {
  gulp.watch('scss/**/*.scss', ['compileSass']);
  gulp.watch('js/main.js', ['concatScripts']);
})

gulp.task('clean', function() {
  del(['dist', 'css/application.css*', 'js/app*.js*']);
});

gulp.task("build", ['minifyScripts', 'compileSass'], function() {
  return gulp.src(["css/application.css", "js/app.min.js", 'index.html',
                   "img/**", "fonts/**"], { base: './'})
            .pipe(gulp.dest('dist'));
});

gulp.task('serve', ["watchFiles"]);

gulp.task("default", ["clean"], function() {
  gulp.start('build');
});

 

Run serve task to start project development:

gulp serve
  • del = require('del');
    Deletes files and directories.
  • gulp.task('clean', function() { ... } );
    A “clean” task is used to delete files that were created by a previous gulp tasks.
    The clean task gets old files out of the way, so there is no conflict between two versions of a gulp task’s output.
  • ... { base: './'})
    The gulp.source method has a base option, that allows you to preserve the directory structure of the files you are introducing to the stream.
  • gulp.start('build');
    gulp.series will replace gulp.start in gulp 4.0
  • gulp.task('serve', ["watchFiles"]);
    Serve application for automatic file refresh during development

When you’re ready for deployment, run gulp:

gulp 

 

Advice
When diving into a set of tasks for a new project, the best approach is in the gulpfile, you work from the bottom up. This way, you can see which tasks depend on which other tasks, starting with the “default” task.