問題描述
我通過在服務(wù)器上使用 gulp 構(gòu)建源文件來部署我的項目.為防止出現(xiàn)緩存問題,最佳做法是為請求 url 添加一個唯一編號,請參閱:防止瀏覽器在 Web 應(yīng)用程序升級時緩存;
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;
在 npm 存儲庫中,我找不到自動向請求添加版本號的工具.我在問是否有人以前發(fā)明過這樣的工具.
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.
可能的實(shí)現(xiàn)如下:
我在 src/
文件夾中有一個文件 index.html,帶有以下腳本標(biāo)簽
I have a file index.html in src/
folder, with following script tag
<script src="js/app.js<!-- %nocache% -->"></script>
在構(gòu)建過程中,它被復(fù)制到 dist/
文件夾,并且注釋被替換為自增號
During build it is copied to dist/
folder, and comment is replaced by autoincrement number
<script src="js/app.js?t=1234"></script>
推薦答案
你可以使用 gulp-version-number
為此.它可以通過將參數(shù)附加到 URL 來將版本號添加到 HTML 文檔中的鏈接腳本、樣式表和其他文件.例如:
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">
變成:
<link rel="stylesheet" href="main.css?v=474dee2efac59e2dcac7bf6c37365ed0">
您甚至不必指定占位符,就像您在示例實(shí)現(xiàn)中展示的那樣.而且是可配置的.
You don't even have to specify a placeholder, like you showed in your example implementation. And it's configurable.
示例用法:
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'));
});
這篇關(guān)于gulp:自動為請求添加版本號以防止瀏覽器緩存的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!