Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gulp: Automatically add version number to request for preventing browser cache

Tags:

I deploy my project by building source files with gulp right on the server. To prevent caching issues, the best practice could be adding a unique number to request url, see: Preventing browser caching on web application upgrades;

In npm repositories, I couldn't find a tool for automatically adding version number to request. I'm asking if someone has invented such tool before.

Possible implementation could be the following:

I have a file index.html in src/ folder, with following script tag

 <script src="js/app.js<!-- %nocache% -->"></script>

During build it is copied to dist/ folder, and comment is replaced by autoincrement number

 <script src="js/app.js?t=1234"></script>
like image 650
Dan Avatar asked Feb 17 '15 23:02

Dan


2 Answers

You can use gulp-version-number for this. It can add version numbers to linked scripts, stylesheets, and other files in you HTML documents, by appending an argument to the URLs. For example:

<link rel="stylesheet" href="main.css">

becomes:

<link rel="stylesheet" href="main.css?v=474dee2efac59e2dcac7bf6c37365ed0">

You don't even have to specify a placeholder, like you showed in your example implementation. And it's configurable.

Example usage:

const $ = gulpLoadPlugins();
const versionConfig = {
  'value': '%MDS%',
  'append': {
    'key': 'v',
    'to': ['css', 'js'],
  },
};

gulp.task('html', () => {
  return gulp.src('src/**/*.html')
    .pipe($.htmlmin({collapseWhitespace: true}))
    .pipe($.versionNumber(versionConfig))
    .pipe(gulp.dest('docroot'));
});
like image 151
Serrano Avatar answered Oct 15 '22 18:10

Serrano


You can use the gulp-rev module. This will append a version number to the files, the version is a hash of the file content, so it will only change if the file changes.

You then output a manifest file containing the mapping between the file e.g. Scripts.js to Scripts-8wrefhn.js.

Then use a helper function when returning the page content to map the correct values.

I have used the above process. However there's another module gulp-rev-all which is an forked extension of gulp-rev which does a little more, e.g. automatic updating of file references in pages.

Documentation here:

  • gulp-rev: https://github.com/sindresorhus/gulp-rev
  • gulp-rev-all: https://www.npmjs.com/package/gulp-rev-all
like image 41
Jack Avatar answered Oct 15 '22 18:10

Jack