gulp-rev-all的Options中的prefix失效的原因

980 阅读2分钟

因工作岗位调整,要回去开发活动页了。活动页我还是喜欢用gulp, 所以重新倒腾工作流。

然后遇到如题的问题。直接看解决办法

gulpfile.js

var gulp = require('gulp'), //gulp插件
    revAll = require('gulp-rev-all'), //修改文件名称
    revdel = require('gulp-rev-delete-original'); //删除rev的源文件
    ...
var basePath = './projects/h5_template';
var publicPath = 'https://mat1.gtimg.com/zj/lyen/2019/test/';
var dist = basePath + '/dist/**'
    ...
    // 增加hash
gulp.task('rev', function () {
  return gulp.src(dist)
        .pipe(revAll.revision({
          dontGlobal: [/share\.(je?pg|png)/],   // 不要做任何修改
          dontRenameFile: [ /\.html$/], // 不要加hash重命名,但是可以修改内部引用地址
          prefix: publicPath
        }))
        .pipe(revdel())
        .pipe(gulp.dest(basePath + '/dist'))
})

开发代码:(只看其中一个文件哈)

<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <link rel="stylesheet" href="../css/style.css" charset="utf-8">
  </head>
  <body>
    测试
    <img src="../imgs/zyc.png">
    <script src="../js/index.js"></script>
  </body>
</html>

打包结果:(很遗憾prefix没有其效果)

<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <link rel="stylesheet" href="../css/style.08173c58.css" charset="utf-8">
  </head>
  <body>
    测试
    <img src="../imgs/zyc.dcc8a3d6.png">
    <script src="../js/index.d6f4c35d.js"></script>
  </body>
</html>

为什么会失效

遇到问题就应该冷静,查看源代码。

node_modules/gulp-rev-all/revisioner.js

...
Revisioner.prototype.updateReferences = function(file) {
    ...
    for (var pathReference in file.revReferencePaths) {
        ...
        if (this.options.transformPath) {
        // Transform path using client supplied transformPath callback,
        pathReferenceReplace = this.options.transformPath.call(
          this,
          pathReferenceReplace,
          reference.path,
          reference.file,
          file
        );
      } else if (this.options.prefix && pathReferenceReplace[0] === "/") {   //问题出在这里,只有引用路径是以'/'开头,才会进入这个if
        // Append with user supplied prefix
        pathReferenceReplace = this.Tool.join_path_url(
          this.options.prefix,
          pathReferenceReplace
        );
      }
        ...
    }
    ...
}
...

源码告诉我们,只有是以'/'开头的引用路径,才会拼接prefix。

那就这样解决

使用 '/' 开头的绝对路径

开发代码:

<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <link rel="stylesheet" href="/css/style.css" charset="utf-8">
  </head>
  <body>
    测试
    <img src="/imgs/zyc.png">
    <script src="/js/index.js"></script>
  </body>
</html>

打包结果:

<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <link rel="stylesheet" href="https://mat1.gtimg.com/zj/lyen/2019/test/css/style.08173c58.css" charset="utf-8">
  </head>
  <body>
    测试
    <img src="https://mat1.gtimg.com/zj/lyen/2019/test/imgs/zyc.dcc8a3d6.png">
    <script src="https://mat1.gtimg.com/zj/lyen/2019/test/js/index.d6f4c35d.js"></script>
  </body>
</html>