Skip to content

Instantly share code, notes, and snippets.

@jonlong
Last active August 29, 2015 14:05
Show Gist options
  • Save jonlong/74bfaccca08f9def4f75 to your computer and use it in GitHub Desktop.
Save jonlong/74bfaccca08f9def4f75 to your computer and use it in GitHub Desktop.
Gulp CDN/Manifest task
var gulp = require('gulp');
var revall = require('gulp-rev-all');
var awspublish = require('gulp-awspublish');
var cloudfront = require('gulp-cloudfront');
var jsoneditor = require('gulp-json-editor');
var secrets = require('../../config/secrets');
var config = require('../../config/app');
var handleErrors = require('../util/handleErrors');
var path = require('path');
var gutil = require('gulp-util');
var fs = require('fs');
var manifest = {};

var aws = {
  key: secrets.cdn.key,
  secret: secrets.cdn.secret,
  bucket: secrets.cdn.bucket,
  region: secrets.cdn.region,
  distributionId: secrets.cdn.distributionId
};

var publisher = awspublish.create(aws);
var headers = {'Cache-Control': 'max-age=315360000, no-transform, public'};

gulp.task('revall-and-upload', function () {

  return gulp.src(config.paths.build.base + '/**')
    .pipe(revall({
      ignore: ['manifest.json'],
      transformFilename: function (file, hash) {
        // This code exists exclusively to create a manifest of relative filenames
        var ext = path.extname(file.path);
        // Can't remember the rationale for truncating the hash here :/
        var filename = hash.substr(0, 5) + '.'  + path.basename(file.path, ext) + ext; // 3410c.filename.ext

        if (file.relative) {
          var relativeDir = file.relative.substring(0, file.relative.lastIndexOf("/") + 1);
          manifest[file.relative] = relativeDir + filename;
        }

        return filename;
      }
    }))
    .pipe(awspublish.gzip())
    .pipe(publisher.publish(headers))
    .pipe(publisher.cache())
    .pipe(awspublish.reporter())
    .pipe(cloudfront(aws));
});

gulp.task('cdn', ['revall-and-upload'], function() {
  var manifestJSON = JSON.stringify(manifest);

  fs.writeFile(config.paths.build.base + '/manifest.json', manifestJSON, function(err) {
    if(err) {
      handleErrors(err);
    } else {
      gutil.log(gutil.colors.green('[create]'), 'manifest.json');
    }
  });
});
<link rel="stylesheet" href="{{css/styles.css | asset_path}}">

Was thinking asset_path would act as a custom filter that matches a key in the manifest file. If you're in a dev environment, it could return the un-cached, uncompressed version. Otherwise, it would return the value of the matching key (which might be something like css/styles-5e328d49sa282jd23sj.css).

If you're pre-compiling HTML (skel-isl style), this probably works best as a custom Swig filter. Could also be route middleware in prototype/non-production situations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment