如何使用Gulp打包时为HTML中CSS链接追加日期版本号参数
Gulp自动追加CSS日期版本号实现步骤
1. 安装依赖
需要用到gulp-replace插件实现字符串替换,执行以下命令安装:
npm install gulp-replace --save-dev
2. 新增日期生成与HTML处理逻辑
在你的gulpfile.js文件中添加如下代码:
// 顶部引入依赖 const gulp = require('gulp'); const replace = require('gulp-replace'); // 生成yyyy-mm-dd格式的日期版本号 function getDateVersion() { const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } // 新增HTML处理任务 gulp.task('process-html', function() { const version = getDateVersion(); return gulp.src('./app/**/*.html') // 匹配app目录下所有HTML文件 // 替换指定CSS引用追加版本号 .pipe(replace('href="app_v2.css"', `href="app_v2.css?v=${version}"`)) // 如果需要给所有CSS引用加版本号,替换成下面这行代码即可 // .pipe(replace(/href="([^"]+\.css)"/g, (match, p1) => `href="${p1}?v=${getDateVersion()}"`)) .pipe(gulp.dest('./dest')); // 输出到构建目标目录 });
注:如果你的Node.js版本低于8.0.0不支持
padStart方法,可将日期生成部分替换为手动补0逻辑:function getDateVersion() { const now = new Date(); const year = now.getFullYear(); const month = now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1; const day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate(); return `${year}-${month}-${day}`; }
3. 整合到现有构建流程
修改你现有的build:dev任务,将HTML处理任务加入执行队列:
// 调整后的构建任务,把process-html加入依赖列表,确保在构建时自动执行 gulp.task('build:dev', ['clean', 'config:development', 'process-html'], function() { gulp.start('create'); });
如果你的create任务本身已经包含HTML文件的拷贝逻辑,也可以直接把replace的处理逻辑添加到create任务中处理HTML的管道流里,避免重复处理文件。
内容的提问来源于stack exchange,提问作者Cyclone
相关产品推荐
相关产品推荐

