Minify your HUGO site - HTML/CSS/JS/XML - the fast way

By Chris Diggs | April 18, 2018

  1. Install NodeJs/NPM

  2. Add this file to your HUGO’s root folder

    • package.json
    {
      "name": "My-Hugo-Site",
      "version": "1.0.0",
      "description": "Check out my awesome site!",
      "main": "index.html",
      "scripts": {
        "build": "gulp build"
      },
      "devDependencies": {
        "babel-preset-es2015": "^6.5.0",
        "babel-register": "^6.26.0",
        "gulp": "^3.9.1",
        "gulp-clean-css": "^3.0.4",
        "gulp-cli": "^1.2.1",
        "gulp-htmlmin": "^1.3.0",
        "gulp-shell": "^0.5.2",
        "gulp-uglify": "^2.1.2",
        "run-sequence": "^1.1.5"
      },
      "babel": {
        "presets": [
          "es2015"
        ]
      },
      "author": "author"
    }


  3. Run npm install in your HUGO’s root folder

    • This will create a folder - node_moduels. Make sure this get’s created!
    • If you’re using git, add this folder to your .gitignore file


  4. Create this file in your HUGO’s root folder

    • gulpfile.babel.js
    var gulp = require('gulp');
    var shell = require('gulp-shell');
    var runSequence = require('run-sequence');
    var htmlmin = require('gulp-htmlmin');
    var cleanCSS = require('gulp-clean-css');
    var uglify = require('gulp-uglify');
    
    gulp.task('hugo-build', shell.task(['hugo']))
    
    gulp.task('minify-html', () => {
      return gulp.src('public/**/*.html')
        .pipe(htmlmin({
          collapseWhitespace: true,
          minifyCSS: true,
          minifyJS: true,
          removeComments: true,
          useShortDoctype: true,
        }))
        .pipe(gulp.dest('./public'))
    })
    
    gulp.task('minify-xml', () => {
      return gulp.src('public/**/*.xml')
        .pipe(htmlmin({
          collapseWhitespace: true,
        }))
        .pipe(gulp.dest('./public'))
    })
    
    gulp.task('minify-css', () => {
      return gulp.src('public/**/*.css')
        .pipe(cleanCSS())
        .pipe(gulp.dest('./public'))
    })
    
    gulp.task('minify-js', () => {
      return gulp.src('public/**/*.js')
        .pipe(uglify({
          preserveComments: 'all',
        }))
        .pipe(gulp.dest('./public'))
    })
    
    gulp.task('build', ['hugo-build'], (callback) => {
      runSequence(['minify-html', 'minify-xml', 'minify-css', 'minify-js'], callback)
    })
    


  5. Run npm run build and watch the magic happen!


    Summary

With just a few steps, we can optimize our static site to provide the best experience to our end-users

Keep in mind, this process can be customized to work with any Static Site Genorator (SSG) - not just HUGO.

Tool chain:

  • NodeJS
  • Gulp
  • Babel
  • HUGO SSG or the SSG of your choice
comments powered by Disqus