Gulp - Optimizing CSS and JavaScript



In this chapter, you will learn how to optimize CSS and JavaScript. Optimizing is required to remove unnecessary data (for e.g. spaces and unused characters) from the source files. It reduces the size of the files and allows them to load faster

Install Plugins to Optimize CSS and JavaScript

Go to “work” directory from your command line and install “gulp-uglify”, “gulp-minify-css” and “gulp-concat” plugins by using the following command −

npm install gulp-uglify gulp-minify-css gulp-concat

Declare Dependencies and Create Tasks

In your configuration file gulpfile.js, first declare the dependencies as shown in the following code.

var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var minify = require('gulp-minify-css');

Next, you need to create tasks for optimizing CSS and JavaScript as shown in the following code.

gulp.task('js', function(){
   gulp.src('src/scripts/*.js')
   .pipe(concat('script.js'))
   .pipe(uglify())
   .pipe(gulp.dest('build/scripts/'));
});

gulp.task('css', function(){
   gulp.src('src/styles/*.css')
   .pipe(concat('styles.css'))
   .pipe(minify())
   .pipe(gulp.dest('build/styles/'));
});

gulp.task('default',['js','css'],function(){
});

The js task will accepts .js files from src/scripts/ folder. It concatenates and uglifies the js files, then produces build/scripts/script.js file.

The CSS task will accept .css files from src/styles/ folder. It concatenates and minifies CSS files, then produces build/styles/styles.css file.

Run the Tasks

The configuration file is set up and ready to execute. Use the following command to run the task.

gulp

On running the task using the above command, you will receive the following result in the command prompt.

C:\work>gulp
[13:16:34] Using gulpfile C:\work\gulpfile.js
[13:16:34] Starting 'js'...
[13:16:34] Finished 'js' after 24 ms
[13:16:34] Starting 'css'...
[13:16:34] Finished 'css' after 6.05 ms
[13:16:34] Starting 'default'...
[13:16:34] Finished 'default' after 5.04 μs
Advertisements