How to do minification and concatenate the files using Gulp JS

Minify and concatenate the JS files using gulp js

Minify and concatenate the multiple JS files into singles file using gulp.

Step 1: Gulp plugin

Declare the gulp plugins in gulpfile.js file.
var gulp = require(‘gulp’);

Step 2: Uglify plugin

Declare the uglify plugin for minifies the required js files.
var uglify = require(‘gulp-uglify’);

Step 3: Concat plugin

Declare the concat plugin for combining the JS files into single file.
Var concat = require(‘gulp-concat’);

Step 4: Creating gulp task

Creating gulp task for Minification and concat process.

gulp.task(‘scripts’, function() {
gulp.src(‘src/*.js’)
.pipe(concat(‘all.min.js’))
.pipe(uglify())
.pipe(gulp.dest(‘dist’));
});

Gulp Task code Explanation:

gulp.src – It defines the input files path for processing
pipe – It is used to chain multiple tasks together using pipe method.
gulp.dest – It defines the output location for processed files.
Concat – This method combines multiples files into single file. We should declare the output
file name within the brackets.

Overall Source Code for Minify and concatenate the JS files using gulp js.


//gulpfile.js file

//Adding dependencies
var gulp = require('gulp');
varuglify = require('gulp-uglify');
varconcat = require('gulp-concat');

//defining tasks
gulp.task('default', function() {  //default is a task name, we can give any name.
	gulp.src('src/*.js')
	.pipe(concat('all.min.js'))
	.pipe(uglify())
	.pipe(gulp.dest('dist'));
});

Project Folder Structure:

Gulp folder structure

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *