Categories
Advanced

Hash File Suffixing

Adding a hash to a file suffix is a common way to force the browser to update its cache.

Angular for example offers this option by default in its build process. Whenever you bundle your code with Angular you will see a hash suffix to the bundled files, which are results of hash functions on the file contents. You can then immediately deploy these files about browser caching without concerns.But not all frameworks offer this. 

Svelte does not automatically bundle files with hash suffixes. You would need to install rollup-plugin-hash, for example. But I feel that a better method is to add the hash after bundling instead.

Often, after I bundle my code, I will need to copy it somewhere else on my machine before I deploy it to a live server.  To do this I use gulp. Gulp is a great tool to create tasks and automate your work. My copy-output task using Gulp looks like this:

var fs = require('fs');
var gulp = require('gulp');
const del = require('del'); 
 
var json = JSON.parse(fs.readFileSync('./dist_folder_details.json')); // this file contains the destination of the bundles on my machine
    gulp.task('copy-output', async () => {
       var distFolder = json['dist-folder-js'];
       await del([distFolder + '/**', '!' + distFolder], 
       {force: true}); // I used del ( 
       https://www.npmjs.com/package/del) to remove   
       the current content
       await new Promise((resolve, reject) => {
         gulp.src('./public/build/*.js')
         .pipe(gulp.dest(distFolder)) // I am copying the 
         new build files to the destination
         .on("end", resolve);
     });
});

So, all I need to do in order to add a hash suffix is to use gulp-hash:

var fs = require('fs');
var gulp = require('gulp');
const del = require('del');
var hash = require('gulp-hash'); // require it
 
var json = JSON.parse(fs.readFileSync('./dist_folder_details.json')); 
 
var json = JSON.parse(fs.readFileSync('./dist_folder_details.json')); 
gulp.task('copy-output', async () => {
    var distFolder = json['dist-folder-js'];
    await del([distFolder + '/**', '!' + distFolder], 
    {force: true}); 
    await new Promise((resolve, reject) => {
        gulp.src('./public/build/*.js')
        .pipe(hash()) // Use it
        .pipe(gulp.dest(distFolder)) 
        .on("end", resolve);
    });
});

Now hashing is integrated into my deploy process. No need to install framework-specific hashing packages.

Thoughts? Comments? Suggestions?  Please let me know below!!

Leave a Reply

Your email address will not be published. Required fields are marked *