返回列表

gulp-rev-collector 始终 替换不成功的问题

默认分类 2018/07/25 12:25

切换到VUE/React后有段时间没有用Gulp了,在处理文件名加md5码时,遇到一个问题,gulp-rev-collector 始终 替换不成功, 一时半会也没找到问题原因,于是尝试把可能的方式都写上去,结果发现,必须匹配上dirReplacements以及文件名,才能成功 替换,问题解决。

Gulp配置文件如下:

var gulp = require('gulp');
var rev = require('gulp-rev');
gulp.task('css', function() {
  return gulp.src('src/css/*.css')
    .pipe(rev())
    .pipe(gulp.dest('dist2/css'))
    .pipe(rev.manifest())
    .pipe(gulp.dest('rev/css'));
});
gulp.task('js', function() {
  return gulp.src('src/js/*.js')
    .pipe(rev())
    .pipe(gulp.dest('dist2/js'))
    .pipe(rev.manifest())
    .pipe(gulp.dest('rev/js'));
});
var revCollector = require('gulp-rev-collector');
// var minifyHTML = require('gulp-minify-html');
gulp.task('html', function() {
  return gulp.src(['rev/**/*.json', 'templates/**/*.html'])
    .pipe(revCollector({
      replaceReved: true,
      dirReplacements: {
        'css': '/dist2/css',
        '/js123/': '/dist2/js234/',
        '/js/': '/dist2/js/',
        'cdn/': function(manifest_value) {
          return '//cdn' + (Math.floor(Math.random() * 9) + 1) + '.' + 'exsample.dot' + '/img/' + manifest_value;
        }
      }
    }))
    // .pipe(minifyHTML({
    //   empty: true,
    //   spare: true
    // }))
    .pipe(gulp.dest('dist2'));
});
//定义默认任务
gulp.task('default', [
  'js', 
  'css', 
  'html', 
  // 'watch', 
  // 'connect'
]);

替换前:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="1.js"></script>
  <script src="/js/1.js"></script>
  <script src="/js123/2.js"></script>
  <script src="/js123/5.js"></script>
  <script src="js\1.js"></script>
  <link rel="stylesheet" href="1.css">
  <link rel="stylesheet" href="css/1.css">
  <link rel="stylesheet" href="css\1.css">
</head>
<body>
  <a>This is a</a>
  <b>This is bb123</b>
</body>
</html>

替换后:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="1.js"></script>
  <script src="/dist2/js/1-e23a761742.js"></script>
  <script src="/dist2/js234/2-d690c0fe63.js"></script>
  <script src="/js123/5.js"></script>
  <script src="js\1.js"></script>
  <link rel="stylesheet" href="1.css">
  <link rel="stylesheet" href="/dist2/css/1-d630e512d1.css">
  <link rel="stylesheet" href="css\1.css">
</head>
<body>
  <a>This is a</a>
  <b>This is bb123</b>
</body>
</html>