Force Refresh of User Files and Scripts Using Gulp Uncache

In this post I will show how to force refresh of CSS, JS and HTML files. I recently came across a issue where Cloudfare was picking up cached files instead of serving the new files. Appending unique strings at the end of file name resolved the issue.

Last post got you started with yeoman webapp generator which uses gulp build process. You might want to add this change to the gulp build process itself so that you don’t need to update the files everytime.

There’s gulp-uncache a plugin that comes to your rescue. Install it using npm.

npm install --save-dev gulp-uncache

Taking an example from the previous post, the index-bundle.js looks something like this,

<!-- build:js scripts/index-bundle.js -->
<script src="scripts/requests.js"></script>
<script src="scripts/webcam.js"></script> 
<script src="scripts/index.js"></script>
<!-- endbuild -->

To use the gulp-cache plugin enclose it between <!-- uncache --> and <!-- enduncache -->. Which makes it,

<!-- uncache -->
<!-- build:js scripts/index-bundle.js -->
<script src="scripts/requests.js"></script>
<script src="scripts/webcam.js"></script> 
<script src="scripts/index.js"></script>
<!-- endbuild -->
<!-- enduncache -->

Next, in gulpfile.js add

var uncache = require('gulp-uncache');

And update the gulp task to,

gulp.task('html', ['styles', 'scripts'], () => {
    return gulp.src('app/*.html')
        .pipe($.useref({
            searchPath: ['.tmp', 'app', '.']
        }))
        .pipe($.if('*.js', $.uglify()))
        .pipe($.if('*.css', $.cssnano({
            safe: true,
            autoprefixer: false
        })))
        .pipe($.if('*.html', $.htmlmin({
            collapseWhitespace: true
        })))
        .pipe(uncache())
        .pipe(gulp.dest('dist'));
});

After running the gulp build command it will look like,

<script src="scripts/index-bundle.js?1401482624657"></script>

For more details about gulp uncache look at its git repo.

This content has been helpful to you?

Thanks for contributing!

Yes No
  • rantie

    It won’t uncache html files as you wrote. So browser can show old HTML. Also this module doesn’t handle images. So old images will be shown to the user. That means the solution handles part of a problem, but bigger part. It will help someone for sure.