Published on: 06 Jan, 2018

How to minify JS and CSS files using Gulp?

Tumblr Digg Google Plus

In this tutorial, you will learn how to minify JS and CSS files using Gulp. So what is exactly a Gulp is? Gulp is a javascript task runner, it can be used to perform automatic tasks such as minifying and bundling files, running unit tests, running code analysis and much more.

So how does the gulp work? The gulp works by defining a js file named gulpfile.js and we define the task that is going to perform by Gulp.Let says we have the following folder structures.

--css (FOLDER)
----style.css (CSS FILE)
----global.css (CSS FILE)

--js (FOLDER)
----scripts.js (JS FILE)
----site.js (JS FILE)



--gulpfile.js (OUR GULP TASK FILE)
We have two folders contain the CSS and js files and we also have two folders that will store the minified the css and js files. We then create a gulp task file and we named it as gulpfile.js. Note this is a static name, so you have named it exactly as gulpfile.js.

Requirements to run Gulp Task Runner

You will need Node.Js installed on your computer and you will need to run the following command to install the node modules.

Please install gulp on your root folder structure.

npm install gulp

This is the required node module to minify css file.

//css minify
npm install --save-dev gulp-minify-css

This is the required node module to minify js file.

//js minify
npm install --save-dev gulp-uglify

Once you installed both modules, you should see there is a node_modules folder created in the above fold structure like below.

If you double click the node_modules folder, you will see there are two modules installed.

Open your gulpfile.js and write the following command.

var gulp 		= require('gulp');
var minifyCSS 	= require("gulp-minify-css");
var minifyJS 	= require("gulp-uglify");
// task
gulp.task('compressCSS', function () {
    gulp.src('./css/*.css') // path to your file

gulp.task('compressJS', function () {
    gulp.src('./js/*.js') // path to your file

Once you copy above code, you can now run the gulp task runner. In this example, the folder structure and node modules installed is located under F:\My TFS\Minify

To compress the CSS files, you just need to run the following command.

gulp compressCSS

To compress the JS files, you just need to run the following command.

gulp compressJS

So where do the compressCSS and compressJS functions come from? They come from the function task name we defined in the gulpfile.js file. If you have any question, feel free to post your question below.


There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.