In the previous article of gulp i.e. Part 1, we learned to write a simple task and run it. Now let’s look more into gulp and write some tasks.
Gulp tasks are a bit more complex than the simple ‘hello’ task. They contain two additional gulp methods and a variety of gulp plugins which can be found at http://gulpjs.com/plugins/
A real gulp task may look like this:
gulp.task('task-name', function () { gulp return.src('source-files') // Get source files with gulp.src .pipe(aGulpPlugin()) // Sends it through a gulp plugin .pipe(gulp.dest('destination')) // Outputs the file in the destination folder })
You can see two additional methods here – gulp.src and gulp.dest.
gulp.src – tells the gulp task what files are to be used for the task and gulp.dest – tells the gulp task where to output the files once the task is completed.
Now let’s build a real task which compiles the LESS files into CSS files.
Let the directory structure be as follows:
Step 1:
| – app
| – css/
| – less/
| – base.less
| – style.less
| – js/
| – index.html
| – package.json
| – gulpfile.js
As you can see, the Less folder includes 2 less files which we need to compile into css files and include them in the css folder. We shall write a gulp task named ‘less‘ for the same.
After you have installed your dependencies, lets require them in your gulp file:
Step 2:
var gulp = require('gulp') var less = require('gulp-less') var path = require('path')
Step 3:
gulp.task('less', function () { return gulp.src('./less/**/*.less') // Get all files ending in .less from less directory and its children directories .pipe(less()) //Use gulp-less .pipe(gulp.dest('./css')); // Destination for the compiled files })
The above task will compile the less files base.less and style.less into base.css and style.less respectively, and save them in the desitination folder ‘css’. The new folder structure is as follows:
| – app
| – css/
| – base.css
| – style.css
| – less/
| – base.less
| – style.less
| – js/
| – index.html
| – package.json
| – gulpfile.js
LESS
@color: #eee;
@fontWeight: bold;h1 {
color: @color;
font-weight: @fontWeight;
}
If you run gulp less, you will see that a style.css file is created in the cs folder. It has the code as follows:
CSS
h1 {
color: #eee;
font-weight: bold;
}
Minifying CSS
Inorder to minify or compress your CSS, you can use gulp-cssmin plugin.
var minifyCSS = require('gulp-cssmin') gulp.task('less', function () { return gulp.src('./less/**/*.less') .pipe(less()) // Use gulp-less .pipe(minifyCSS()) // Using gulp-cssmin .pipe(gulp.dest('./css')); // Destination for the compiled files })