Gulp中的缓存破坏仅适用于index.html更改,而非css或js更改

rhfm7lfc  于 2022-12-08  发布在  Gulp
关注(0)|答案(2)|浏览(199)

我的浏览器缓存有问题,所以我试图更新index.html文件,如果css,js或html文件被更改。
我要更新的行是:

<link rel="stylesheet" href="styles/main.css?cb=123" />

更重要的是**?cb=123部分
基本上,我的gulp函数查找'cb=',并根据日期和时间用一个新的数字更新它。
如果我使用下面的gulpfile.js,这个index.html更新得很好。对index.html文件的任何更改都会导致一个新的
cb**编号。

// --------------------------------------------
// Gulp Loader
// --------------------------------------------

const {
    src,
    dest,
    task,
    watch,
    series,
    parallel
  } = require("gulp");

  // --------------------------------------------
  // Dependencies
  // --------------------------------------------

  const homedir = require("os").homedir();
  var path = require("path");
  var pathDir = require("path").resolve(__dirname, "../../");
  var parentDir = path
    .dirname(pathDir)
    .split(path.sep)
    .pop();

  var newParent = parentDir.split(" ").join("_");

  var parentdir = path.basename(path.dirname(pathDir));
  parentdir = parentDir.replace(/[^\w]/g, "");
  parentdir = parentDir.replace(/[^\w]/g, "").toLowerCase();

  // HTML plugins
  let htmlmin = require("gulp-htmlmin");

  // CSS / SASS plugins
  let sass = require("gulp-sass");
  let autoprefixer = require("autoprefixer");
  let minifycss = require("gulp-clean-css");
  let postcss = require("gulp-postcss");
  let cssnano = require("cssnano");

  // JSS / plugins
  let uglify = require("gulp-uglify");

  // Utility plugins
  let concat = require("gulp-concat");
  let del = require("del");
  let plumber = require("gulp-plumber");
  let sourcemaps = require("gulp-sourcemaps");
  let rename = require("gulp-rename");
  let fileinclude = require("gulp-file-include");
  var replace = require('gulp-replace');

  // Browser plugins
  let browserSync = require("browser-sync").create();

  // Images plugins
  let imagemin = require("gulp-imagemin");
  let embedSvg = require("gulp-embed-svg");

  // --------------------------------------------
  // Project Variables
  // --------------------------------------------

  let htmlSrc = "source/";
  let htmlDest = homedir + "/sites/blog/";

  let incSrc = "source/includes/";

  let styleSrc = "source/styles/";
  let styleDest = homedir + "/sites/blog/styles/";

  let vendorSrc = "source/scripts/vendors/";
  let scriptSrc = "source/scripts/";
  let scriptDest = homedir + "/sites/blog/scripts/";

  let imageSrc = "source/images/";
  let imageDest = homedir + "/sites/blog/images/";

  let fontSrc = "source/fonts/";
  let fontDest = homedir + "/sites/blog/fonts/";

  // --------------------------------------------
  // Tasks
  // --------------------------------------------

  // CSS
  function css(done) {
    src([
      styleSrc + 'main.scss',
    ])

      .pipe(sass({
        outputStyle: 'compressed'
      }))
      .pipe(plumber())
      .pipe(dest(styleDest));
    done();
  };

  // JS
  function js(done) {
    src([scriptSrc + "*.js", vendorSrc + "*.js"])
      .pipe(
        rename({
          basename: "main",
          suffix: ".min"
        })
      )
      .pipe(plumber())
      .pipe(uglify())
      .pipe(dest(scriptDest));
    done();
  }

  // HTML
  function html(done) {
    var cbString = new Date().getTime();
    src(htmlSrc + "index.html")
      .pipe(
        fileinclude({
          prefix: "@@",
          basepath: "source/includes"
        })
      )
      .pipe(replace(/cb=\d+/, 'cb=' + cbString))
      .pipe(
        embedSvg({
          root: "./source/images/",
          selectors: ".inline-svg"
        })
      )
      .pipe(
        htmlmin({
          collapseWhitespace: true,
          minifyCSS: true,
          minifyJS: {
            compress: {
              drop_console: true
            }
          },
          processConditionalComments: true,
          removeComments: true,
          removeEmptyAttributes: true,
          removeScriptTypeAttributes: true,
          removeStyleLinkTypeAttributes: true,
          processScripts: ["application/ld+json"]
        })
      )
      .pipe(dest(htmlDest));
    done();
  }

  // IMAGES
  function img(done) {
    src(imageSrc + "*")
      .pipe(imagemin())
      .pipe(dest(imageDest));
    done();
  }

  // FONTS
  function fonts(done) {
    src(fontSrc + "*").pipe(dest(fontDest));
    done();
  }

  // --------------------------------------------
  // Watch for changes
  // --------------------------------------------

  function watcher() {
    // Serve files from the root of this project
    browserSync.init({
      server: {
        baseDir: homedir + "/sites/blog/",
      },
      notify: false
    });

    watch(htmlSrc, series(html)).on("change", browserSync.reload);
    watch(styleSrc, series(css)).on("change", browserSync.reload);
    watch(scriptSrc, series(js)).on("change", browserSync.reload);
    watch(imageSrc, series(img)).on("change", browserSync.reload);
    watch(imageSrc, series(fonts)).on("change", browserSync.reload);
  }

  // use default task to launch Browsersync and watch JS files
  var build = parallel(css, js, html, img, fonts, watcher);
  task("default", build);

但是,只有当index.html文件被更改时,这个数字才会更新,所以回到绘图板上。
现在我想在更新js或css文件时更新数字,我尝试从html函数中取出下面的行并赋予它它它的函数:

.pipe(replace(/cb=\d+/, 'cb=' + cbString))

就像这样:

// Cachebust
function cacheBustTask(done) {
  var cbString = new Date().getTime();
  src(htmlSrc + "index.html")
    .pipe(replace(/cb=\d+/g, 'cb=' + cbString))
    .pipe(dest(htmlDest));
  done();
}

但这会阻碍网站。
有没有什么想法,我可以让任务cacheBustTaskhtml任务一起工作。
下面是完整更新的gulpfile.js,其中包含单独的cacheBustTask任务/函数

krugob8w

krugob8w1#

假设您有以下文件夹结构:

src
  js
    index.js
  scss
    index.scss
public
about.html     << target this one
index.html     << target this one

并且您希望将缓存破坏仅添加到.js.css文件
皈依说:

<script src="dist/index.js?cb=0"></script>

转换为:

<script src="dist/index.js?cb=1607437629110"></script>

在您gulpfile.js中使用该文件

function cacheBustTask(){
    return src(['index.html', 'about.html'])
        .pipe(replace(/(\.(css|js)\?cb=)\d+\b/g, `$1${Date.now()}`))
        .pipe(dest('.'));
}

如果要将所有.html文件作为目标,请使用通配符**

return src(["**/*.html"])

附加注解:

因为每次你做一些改变,你的管道触发这种修改,你可能会遇到这个问题或推送到Git文件,你实际上没有触及。
因此,只有在为生产进行构建时,您才应添加到您的管道中以运行上述内容。
因此,基本上在开发模式下(在src文件夹中),您应该始终看到后缀?cb=0,并且只有在为生产构建项目时,才会在最终进入dist的文件中看到以?cb=1607437629110为后缀的时间戳。

rxztt3cl

rxztt3cl2#

有一些插件可以做到这一点,我使用gulp-version-number

const addVersionString = require("gulp-version-number");

const versionConfig = {
  "value": "%DT%",
  "append": {
    "key": "v",
    "to": ["css", "js"],
  },
};

function processHTML() {
  return gulp.src(paths.html.src)
    .pipe(print())

    // modifyHTMLlinks: remove browserSync script link
    // update css/js links to .min.css or .min.js
    .pipe(modifyHTMLlinks())

    .pipe(stripComments.html(stripOptions))

    // add ?v=dateTime stamp to css and js links
    .pipe(addVersionString(versionConfig))

    .pipe(gulp.dest(paths.html.deploy));
}

最后你会说

<link rel="stylesheet" href="css/styles.min.css?v=20201206182221">
  <script src="js/app.min.js?v=20201206182221"></script>

我也没有将它用于html文件,因此您必须修改配置来添加它。

相关问题