如何在Gulp任务中的HTML文件之后重命名zip文件

eller叫者

我正在尝试使用gulp-zip压缩dist文件夹中的所有文件,并希望在该目录中唯一的html文件之后动态命名该zip文件。这是我尝试使用gulp文件名的尝试,但是没有运气。

const rename = require('gulp-rename');
const zip = require('gulp-zip');
var filenames = require('gulp-filenames');

gulp.task('zipp', function(){
	gulp.src('dist/*')
			.pipe(zip('_final.zip'))
			.pipe(rename({prefix:getHtmlName()}))
			.pipe(gulp.dest('./dist'))
})

function getHtmlName(){
	gulp.src("./src/*.html")
	.pipe(filenames("html"))
	.pipe(gulp.dest("./dist"));
	return filenames.get("html");
}

标记

有两种方法:

const gulp = require('gulp');
const rename = require('gulp-rename');
const zip = require('gulp-zip');
const filenames = require('gulp-filenames');

// run the getHTMLname task first, filenames will then have the data stored in an array

gulp.task('zipp', ['getHTMLname'], function () {

    return gulp.src('dist/*')
    .pipe(zip('_final.zip'))

    // rename gets the file passing through it, in this case '_final.zip'

    .pipe(rename(function (path) {

      // retrieve the array of string filenames, use the first and only one in the array
      // and get the basename via split

      path.basename = filenames.get("html")[0].split('.')[0] + path.basename;
    }))

        .pipe(gulp.dest('./dist'))
})

gulp.task('getHTMLname', function () {
  return gulp.src("./dist/*.html")
    .pipe(filenames("html"))
});

//  **************************************************************

const gulp = require('gulp');
const rename = require('gulp-rename');
const zip = require('gulp-zip');

const glob = require("glob");
const path = require('path');

gulp.task('zipp', function () {

  return gulp.src('dist/*')
    .pipe(zip('_final.zip'))

    .pipe(rename(function (file) {

      // glob.sync returns an array, get the first member of that array
      // path.basename('string', '.html') returns the name of the file without the extension

      var temp = path.basename(glob.sync("./dist/*.html")[0], '.html');
      file.basename = temp + file.basename;
    }))
    .pipe(gulp.dest('./dist'))
});

如果您确实要使用gulp文件名,请使用********上方的代码。“ getHTMLname”任务必须首先运行-即gulp-filenames从您提供的任何源目录中构建其文件名数组。该阵列以后可以在后续任务中的任何地方使用。

但是,我建议使用glob和path模块的第二种方法,无论如何都应该学习。第二种方法不需要单独的任务,它只是获取您想要在同一任务中显示的html文件名,因此更加简单。另外,当我安装gulp-filenames时,它正在使用大量不推荐使用的模块,因此非常需要对其进行更新。它现在可以使用,但是在您更新节点等时可能无法使用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章