Minify Assets (JavaScript/Css/Images) With Gulp 4

Gulp is a frontend development tool.

It is primarily used as a task runner for doing repetitive, tedious tasks, when you are doing frontend web development.

Gulp can be used to minify assets – JavaScript, CSS, Images and even HTML code.

To minimise assets – images/css/javascript with gulp, you can use the gulp-uglify and gulp-imagemin plugins.

These plugins can be used to compress and optimise your images and JavaScript files, which can help to reduce their size and improve the performance of your website.

Here is an example of how you can use these plugins with gulp:

Open a terminal in the document root of your project.

Then type the following command to install the gulp-uglify and gulp-imagemin plugins using npm:

npm install gulp-uglify gulp-imagemin --save-dev

In your gulpfile.js, require the gulp-uglify and gulp-imagemin plugins

const uglify = require('gulp-uglify');
const imagemin = require('gulp-imagemin');

Create a task to minimise your JavaScript files using gulp-uglify:

gulp.task('scripts', () => {
  return gulp.src('src/scripts/*.js')

Create a task to minimise your images using gulp-imagemin:

gulp.task('images', () => {
  return gulp.src('src/images/*')

Run the tasks in your terminal to minimise your assets:

gulp scripts
gulp images

Note that this is just one way to minimise your assets with gulp.

There are many other plugins and techniques that you can use to achieve the same result.

Why minify assets?

JavaScript, CSS, Images, HTML code all add to web page size. Minimising these assets lower page load time which is good for user experience.