combine-and-minify-all-css-and-javascript-with-gulp

Combine and Minify all CSS and JavaScript with Gulp

combine-and-minify-all-css-and-javascript-with-gulp

When building a large web application or hybrid mobile application ( Cordova / Ionic Mobile application) , you will find that there are lot of CSS and JavaScript files which will create site performance issues and increase number of requests.

Google Minify Resources explains that

Minification refers to the process of removing unnecessary or redundant data without affecting how the resource is processed by the browser – e.g. code comments and formatting, removing unused code, using shorter variable and function names, and so on.

According to Google page speed rules, HTML pages are recommended to have “Minify Javascript” and “Minify CSS”. In most cases, Google recommend combining all CSS and Javascript files, so that the number of requests are decreased. (Refers to below image).

minify-cssandjs

With Gulp, you can improve the overall performance of your sites and applications by combining all CSS and JavaScript into one file then minifying CSS and JavaScript files.

For Introduction and Installation of gulp, please look at my previous post Introduction to Gulp Js

For this article, I have created a sample project structure that can help you address the performance issues.

  • Public
    • CSS
      • css
      • css
      • css
      • css
    • JS
      • js
      • js
      • js
      • js
    • dest
      • css
      • js
    • gulpfile.js
  • index.html

Now everything is ready, Let’s start,

To achieve the desired results of project scripts, you will need to install ‘gulp-concat’, ‘gulp-uglify’ and ‘gulp-uglifycss’. Open command prompt, then install following plugins

npm install –save-dev  gulp-concat  gulp-uglify  gulp-uglifycss

The Plugins are

gulp-concat :  Used to combine multiple files into one file. For Example

gulp-uglify   : Used to minify all JS files.

gulp-uglifycss :  Used to minify all CSS files.

Using Gulp, Let’s initialize all gulp plugins into JavaScript variables and start creating tasks in gulpfile.js

Run these tasks in command prompt with default task as one task

To run individually,

By running the code in the above manner, all JS files from JS folder are combined in to one file and renames as app.js and moved to dest/js/ folder. Similarly, all CSS files from CSS folder are combined into one file and renamed as app.css and moved to dest/css/ folder.

If you include this files in your ‘index.html’ file then you will experience much better performance from your app!

No Comments

Post A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.