Search Icon, Magnifying Glass

Marmanold.com

Graduation CapHeartQuestion MarkMagnifying Glass

Build, Minify, and Upload Hugo to S3

Though I’m not a huge fan of JavaScript, I include a small bit of it in this site to track page views and to generate the tag cloud on my search page. Since my project had already been polluted with JavaScript, I decided a while back to go all in and use WebPack and Gulp to bundle my JavaScript code, build my Hugo site, minify everything, and then upload the whole thing to S3.

Below is my gulpfile.js that accomplishes all of this. By adding gulp build and gulp upload to the scripts section of my package.json I can build, minify, and upload my site updates via two simple commands: yarn run build && yarn run upload.

var gulp = require('gulp');
var htmlmin = require('gulp-htmlmin');
var runSequence = require('run-sequence');
var shell = require('gulp-shell');
var webpack = require('webpack');
var gulpWebpack = require('webpack-stream');
var csso = require('gulp-csso');
var jsonminify = require('gulp-jsonminify');

var s3 = require('gulp-s3-upload')({"accessKeyId": "REDACTED", "secretAccessKey": "REDACTED"});

gulp.task('hugo-build', shell.task(['hugo']));

gulp.task('minify-html', () => {
  return gulp.src('public/**/*.html')
    .pipe(htmlmin({
      collapseWhitespace: true,
      removeComments: true, 
      html5: true, 
      minifyCSS: true,
      minifyJS: true,
      useShortDoctype: true,
    }))
    .pipe(gulp.dest('./public'));
});

gulp.task('minify-css', () => {
    return gulp.src('./static/css/style.css')
        .pipe(csso())
        .pipe(gulp.dest('./public/css/'));
});

gulp.task('minify-json', function () {
    return gulp.src(['public/**/*.json'])
        .pipe(jsonminify())
        .pipe(gulp.dest('./public'));
});

gulp.task('webpack', () => {
  return gulp.src('js_src/entry.js')
    .pipe(gulpWebpack(require('./webpack.config.js'), webpack))
    .pipe(gulp.dest('static/js/'));
});

gulp.task('upload', () => {
    return gulp.src('./public/**')
        .pipe(s3({
            Bucket: 'REDACTED', 
            ACL:    'public-read'
        }, {
            maxRetries: 5
        }));
});

gulp.task('build', (callback) => {
  runSequence('webpack', 'hugo-build', ['minify-html', 'minify-css'], 'minify-json', callback);
});