Working on a future blog post I hit some problems involving files that needed to be moved around as part of build process. This is one of the problems that gulpĀ solves.
What is gulp?
Gulp is a task runner that utilizes node. The core idea behind task runners is automation. Have lessĀ that needs compiled into css, minified and output into the proper directory? That is a great use case for a task runner.
Gulp is not the only task runner out there. Grunt is another option and has actually been around longer. I am using gulp because it is the default in Visual Studio 2015. Google gulp vs grunt and decide which is right for you.
Installation
- Install node if needed from this site.
- From the console install gulp using npm install gulp -g
Project setup
Next add a gulpfile.js the root of the project whereĀ gulp is to be used. If using ASP.NET 5Ā this file will already exist and will include a few prebuilt tasks. If you are not using ASP.NET 5 the following is a mimimum gulpfile fromĀ the official getting started guide.
var gulp = require('gulp'); gulp.task('default', function() { // place code for your default task here });
Also add gulp to the devDependencies section of the project’s package.json file. Since Visual Studio handles edits to package.json so nicely (intellisense and automatic package restore) I tend to edit the file manually instead of using npm.
"devDependencies": { "gulp": "3.9.0" }
Plugins
The base gulp APIĀ only contains 4 functions (src, dest, task and watch) and doesn’t do a whole lot on its own. This is where plugins come in. Gulp has a ton of plugins that do all sorts of useful things. For example, the default gulpfile.js provided by Visual Studio has a min:js task that used gulp-concat and gulp-uglify to combine javascript files and then minifyĀ the result.
Example gulpfile for minification of javascript
The following is a full gulpfile based on the default file generated by Visual Studio stripped down to just the bits needed for the min:js task.
"use strict"; var gulp = require("gulp"), concat = require("gulp-concat"), uglify = require("gulp-uglify"); var paths = { webroot: "./wwwroot/" }; paths.js = paths.webroot + "js/**/*.js"; paths.minJs = paths.webroot + "js/**/*.min.js"; paths.concatJsDest = paths.webroot + "js/site.min.js"; gulp.task("min:js", function () { return gulp.src([paths.js, "!" + paths.minJs], { base: "." }) .pipe(concat(paths.concatJsDest)) .pipe(uglify()) .pipe(gulp.dest(".")); });
The above will pull all the javascript files from wwwroot/js and its subfolders and combine them and output the results to site.min.jsĀ in the wwwroot/js folder.