在juqery和easyui 盛行的年代许多项目采用纯静态页面去构建前端框架从而实现前后端分离的目的。项目开发周期内往往会频繁修改更新某个文件,当你将文件更新到服务器后客户端由于缓存问题而出现显示异常的情况,这时候你会经常让客户清楚缓存,然后开始了漫长的教学过程,,,
我们也会尝试在静态资源后面加上 ”index.html?v=“ new Date().getTime(); 来解决这个问题,效果也颇为良好,但当项目为已有项目时会是个相当头疼的问题,这个时候我们就会希望有一个全局构建工具来帮我们批量添加,优秀的程序员就开发的 静态资源版本构建工具 gulp webpack 等

想要达到的效果

添加前
<script src="index.js"></script>
<a href="index.html"></a>
<a href="index.html?id=10"></a> 添加后
<script src="index.js?v=78y65gv6e2"></script>
<a href="index.html?v=998776654e"></a>
<a href="index.html?v=9877657wa2&id=10"></a>

开始:

  • 安装gulp和gulp插件(前提:需要安装node.js)

打开node命令行,cd 进入到项目根文件夹(若安装失败,推荐国内的淘宝npm镜像,教程:https://blog.csdn.net/quuqu/article/details/64121812,使用方法将npm改为cnpm)

    分别一次执行

    • npm install –save-dev gulp

    • npm install –save-dev gulp-rev
    • npm install –save-dev gulp-rev-collector
    • npm install –save-dev gulp-asset-rev
    • npm install –save-dev run-sequence
  • 在项目跟目录新建 gulpfile.js 文件
var gulp = require('gulp'),
assetRev = require('gulp-asset-rev'),
runSequence = require('run-sequence'),
rev = require('gulp-rev'),
revCollector = require('gulp-rev-collector');
var cssSrc = './src/css/**/*.css',
jsSrc = './src/js/**/*.*';
contentSrc = './src/content/*.html';
grfSrc = './src/grf/*.grf';
imagesSrc = './src/images/*.*';
resourceSrc='./src/resource/*.*';
//css
gulp.task('css', function () {
gulp.src(cssSrc)
.pipe(rev())
.pipe(gulp.dest('./dist/css'))
.pipe(rev.manifest({ meger: true }))
.pipe(gulp.dest('./dist/css')) });
//js
gulp.task('js', function () {
gulp.src(jsSrc)
.pipe(rev())
.pipe(gulp.dest("./dist/js"))
.pipe(rev.manifest({ meger: true }))
.pipe(gulp.dest('./dist/js'))
});
//html
gulp.task('content', function () {
gulp.src(contentSrc)
.pipe(rev())
.pipe(gulp.dest("./dist/content"))
.pipe(rev.manifest({ meger: true }))
.pipe(gulp.dest('./dist/content'))
});
//grf
gulp.task('grf', function () {
gulp.src(grfSrc)
.pipe(rev())
.pipe(gulp.dest("./dist/grf"))
.pipe(rev.manifest({ meger: true }))
.pipe(gulp.dest('./dist/grf'))
});
//iamges
gulp.task('images', function () {
gulp.src(imagesSrc)
.pipe(rev())
.pipe(gulp.dest("./dist/images"))
.pipe(rev.manifest({ meger: true }))
.pipe(gulp.dest('./dist/images'))
});
//其他资源
gulp.task('resource', function () {
gulp.src(resourceSrc)
.pipe(rev())
.pipe(gulp.dest("./dist/resource"))
.pipe(rev.manifest({ meger: true }))
.pipe(gulp.dest('./dist/resource'))
});
//其他固定名称资源
gulp.task('copy', function () {
gulp.src(['./src/AilinkFlashLinker.js','./src/favicon.ico','./src/LXFlashLinker.swf','./src/LXFlashSWITCH.swf'])
.pipe(gulp.dest('./dist'));
});
//根据json配置信息生成全新html
gulp.task('revHtml', function () {
gulp.src(['./dist/js/*.json', './dist/css/*.json', './dist/content/*.json', './dist/grf/*.json', './dist/images/*.json','./dist/resource/*.json', './src/**/*.html'])
.pipe(revCollector({ replaceReved: true }))
.pipe(gulp.dest('./dist'));
});
//执行
gulp.task('default', function (done) {
condition = false;
runSequence(
['css'],
['js'],
['content'],
['grf'],
['images'],
['resource'],
['copy'],
['revHtml'],
done);
});

修改插件

»>1

打开node_modules\gulp-rev\index.js

134行: manifest[originalFile] = revisionedFile;

更新为: manifest[originalFile] = originalFile + ‘?v=’ + file.revHash;

»>2

打开 node_modules\rev-path\index.js

注意:原文这里的路径是打开nodemodules\gulp-rev\nodemodules\rev-path\index.js,根据你的具体情况进行修改。

9行: return modifyFilename(pth, (filename, ext) => ${filename}-${hash}${ext});

更新为:return modifyFilename(pth, (filename, ext) => ${filename}${ext});

17行: return modifyFilename(pth, (filename, ext) => filename.replace(new RegExp(-${hash}$), ‘’) + ext);

更新为: return modifyFilename(pth, (filename, ext) => filename + ext);

»>3

打开node_modules\gulp-rev-collector\index.js

40行:var cleanReplacement =  path.basename(json[key]).replace(new RegExp( opts.revSuffix ), ‘’ );

更新为:var cleanReplacement =  path.basename(json[key]).split(‘?’)[0];

»>4

打开node_modules\gulp-assets-rev\index.js

78行: var verStr = (options.verConnecter || “-“) + md5;

更新为:var verStr = (options.verConnecter || “”) + md5;

80行: src = src.replace(verStr, ‘’).replace(/(.[^.]+)$/, verStr + “$1”);

更新为:src=src+”?v=”+verStr;

»>5

打开node_modules\gulp-rev-collector\index.js

173行regexp: new RegExp( prefixDelim + pattern, ‘g’ ),

更新为 regexp: new RegExp( prefixDelim + pattern + ‘(\?v=\w{10})?’, ‘g’ )

上述更改后在项目所在根目录执行 gulp 两次,第一次是根据修改生成 json 文件,第二次是根据json对照文件生成全新html 文件

生成后你会发现 原本 html?id=5 生成后 html?v=25454454?id=5 这并不是我们想要的结果,我们希望重新生成html后变为 html?v=25454454&id=5

打开node_modules\gulp-rev-collector\index.js

在173行下面新增 regexpEx: new RegExp( prefixDelim + pattern + ‘(\?v=\w{10})(\?)?’, ‘g’ ),

在176行下面新增 replacementEx: ‘$1’ + manifest[key]+’&’

在 193行下面新增 src = src.replace(r.regexpEx,r.replacementEx);

最后我们再执行两次 gulp 如愿得到想要的结果(美中不足的是在head头引用静态文件的位置版本号后面都加上了一个&,单不会影响正常使用)

2019年5月20日12:53:55 修改

有人说 gulp 太老,为何不用 webpack,我想说工具选择合适自己的就行,不在乎什么时候的

Gulp 给所有静态文件引用加版本号的更多相关文章

  1. Asp-Net-Core开发笔记:使用NPM和gulp管理前端静态文件

    前言 本文介绍的是AspNetCore的MVC项目,WebApi+独立前端这种前后端分离的项目就不需要多此一举了~默认前端小伙伴是懂得使用前端工具链的. 为啥要用MVC这种服务端渲染技术呢? 简单项目 ...

  2. Web前端性能优化——如何有效提升静态文件的加载速度

    WeTest 导读 此文总结了笔者在Web静态资源方面的一些优化经验. 一.如何优化 用户在访问网页时, 最直观的感受就是页面内容出来的速度,我们要做的优化工作, 也主要是为了这个目标.那么为了提高页 ...

  3. web前端性能优化,提升静态文件的加载速度

    原文地址:传送门 WeTest 导读 此文总结了笔者在Web静态资源方面的一些优化经验. 如何优化 用户在访问网页时, 最直观的感受就是页面内容出来的速度,我们要做的优化工作, 也主要是为了这个目标. ...

  4. Django中静态文件引用优化

    静态文件引用优化 在html文件中是用django的静态文件路径时,一般会这么写: <script type="text/javascript" src="/sta ...

  5. Django-2- 模板路径查找,模板变量,模板过滤器,静态文件引用

    模板路径查找 路径配置 2. templates模板查找有两种方式 2.1 - 在APP目录下创建templates文件夹,在文件夹下创建模板 2.2 - 在项目根目录下创建templates文件夹, ...

  6. Django模板变量及静态文件引用

    一.模板变量传递 1.视图向模板传递变量 视图中的列表,数组,字典,函数均可以传递给模板 在视图中定义变量通过render(content{‘name’ : value})传递给模板 模板通过{{  ...

  7. django在关闭debug后,admin界面 及静态文件无法加载的解决办法

    当debug为true的时候,ALLOWED_HOSTS是跳过不管用的.所以这里需要将debug关掉,令debug=false,ALLOWED_HOSTS=[ '*' ]表示所有的主机都可以访问 开启 ...

  8. django 项目运行时static静态文件不能加载问题处理

    一.首先检查网页中的加载路径是否正确,如果和文件所在路径不一致,就把html改下路径 二.加载路径和文件实际路径一致,看下配置文件: STATIC_URL = '/static/'STATIC_ROO ...

  9. Django模板变量,过滤器和静态文件引用

    模版路径查找 首先去settings.py里面找TEMPLATES ,在TEMPLATES下面找DIRS,找到就返回,没找到就继续往下,如果APP_DIRS设置为为Ture,那么就会到上面 INSTA ...

随机推荐

  1. GEO Gene Expression Omnibus

    GEO  Gene Expression Omnibus 基因表达数据库 网址:https://www.ncbi.nlm.nih.gov/geo/ GEO的数据存储方式 GEO数据库具体存放四类数据: ...

  2. Hotspot对象的内存布局

    对象头 class oopDesc { ... private: volatile markOop _mark; union _metadata { Klass* _klass; narrowKlas ...

  3. Swagger-BootStrap-UI生成的接口文档如何加Basic校验

    首先我们来看看swagger-bootstrap-ui的效果,如图所示: 看起来是不是比Swagger要大气的多. 回到重点上,为什么要给接口文档加密呢? 只对内开放,不对外开放,防止被第三方非公司人 ...

  4. bind named.conf 的理解

    [root@46 /]#yum -y install bind bind-chroot bind-libs bind-utils caching-nameserver目录说明/var/named/ch ...

  5. SpringMVC(十六):如何使用编程方式替代/WEB-INF/web.xml中的配置信息

    在构建springmvc+mybatis项目时,更常用的方式是采用web.xml来配置,而且一般情况下会在web.xml中使用ContextLoaderListener加载applicationCon ...

  6. 010 vue使用render方法渲染组件

    1.普通的组件渲染方式 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

  7. 解决:File "/usr/lib/python2.7/site-packages/more_itertools/more.py", line 340 def _collate(*iterables, key=lambda a: a, reverse=False): 的报错

    cyberb commented on 15 Apr Traceback (most recent call last): File "/snap/users/x1/python/bin/l ...

  8. Spring boot与Spring cloud之间的关系

    Spring boot 是 Spring 的一套快速配置脚手架,可以基于spring boot 快速开发单个微服务,Spring Boot,看名字就知道是Spring的引导,就是用于启动Spring的 ...

  9. HTML5 VUE单页应用 SEO 优化之 预渲染(prerender-spa-plugin)

    前言:当前 SPA 架构流行的趋势如日中天,前后端分离的业务模式已经成为互联网开发的主流方式,但是 单页面 应用始终存在一个痛点,那就是 SEO, 对于那些需要推广,希望能在百度搜索时排名靠前的网站而 ...

  10. 发布微信小程序体验版

    小程序这么火,一直没有做过.因为公司有个业务需要做小程序就顺带学习了一把. 1)本次是采用<微信开发者工具 Stable v1.02.1904090>进行的开发: 2)前端使用的是微信官方 ...