gvmohzibat
9/16/2019 - 3:27 PM

gulp minify html css js image

Simple gulpfile.js

Simple gulpfile.js that minifies everything and also uses autoprifixer and imagemin

Usage

  • Put every file in src folder.
  • Download the package.json and gulpfile.js provided in comments below and copy them beside the src folder.
  • Your structure should look like this:
 ├─ src/
 ├─ gulpfile.js
 ├─ package.json
  • Run these commands:
npm install
npm run build
  • Minified project is ready in dist folder
var gulp = require('gulp'),
  del = require('del'),
  uglify = require('gulp-uglify'),
  minifyCSS = require('gulp-minify-css'),
  imagemin = require('gulp-imagemin'),
  autoprefixer = require('gulp-autoprefixer'),
  plumber = require('gulp-plumber'),
  htmlmin = require('gulp-htmlmin'),
  cache = require('gulp-cache');

const paths = {
  src: 'src',
  dist: 'dist'
};

gulp.task('html', function() {
  const src = `${paths.src}/**/*.html`;
  return gulp
    .src(src)
    .pipe(htmlmin({ collapseWhitespace: true, minifyCSS: true, minifyJS: true, minifyURLs: true, removeComments: true }))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('css', function() {
  const src = `${paths.src}/**/*.css`;
  return gulp
    .src(src)
    .pipe(plumber())
    .pipe(autoprefixer())
    .pipe(minifyCSS())
    .pipe(gulp.dest(paths.dist));
});

gulp.task('js', function() {
  const src = `${paths.src}/**/*.js`;
  return gulp
    .src(src)
    .pipe(plumber())
    .pipe(uglify())
    .pipe(gulp.dest(paths.dist));
});

gulp.task('image', function() {
  const src = ['jpg', 'png', 'gif', 'jpeg'].map(ext => `${paths.src}/**/*.${ext}`);
  return gulp
    .src(src)
    .pipe(
      cache(
        imagemin({
          optimizationLevel: 5,
          progressive: true,
          interlaced: true
        })
      )
    )
    .pipe(gulp.dest(paths.dist));
});

gulp.task('files', function() {
  const src = [`${paths.src}/**/*`, ...['html', 'css', 'jpeg', 'jpg', 'png', 'gif', 'js'].map(ext => `!${paths.src}/**/*.${ext}`)];
  return gulp.src(src).pipe(gulp.dest(paths.dist));
});

gulp.task('del', function() {
  return del(paths.dist);
});

gulp.task('build', gulp.series('del', 'files', 'html', 'css', 'js', 'image'));
{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build": "gulp build"
  },
  "browserslist": [
    "last 2 versions",
    "ie 10",
    "ie 11",
    "android 2.3",
    "android 4",
    "opera 12"
  ],
  "license": "ISC",
  "devDependencies": {
    "del": "^5.1.0",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^7.0.0",
    "gulp-cache": "^1.1.3",
    "gulp-htmlmin": "^5.0.1",
    "gulp-imagemin": "^6.1.0",
    "gulp-minify-css": "^1.2.4",
    "gulp-plumber": "^1.2.1",
    "gulp-uglify": "^3.0.2",
    "imagemin-jpegtran": "^6.0.0",
    "imagemin-pngquant": "^8.0.0"
  }
}