Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

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

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'));
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...