首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Gulp任务中的HTML文件之后重命名zip文件

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

Stack Overflow用户
提问于 2018-03-13 22:59:58
回答 1查看 148关注 0票数 1

我试图使用gulp压缩我的dist文件夹中的所有文件,并希望以该目录中唯一的html文件的名称动态命名zip文件。这是我尝试使用的吞咽文件名,但没有运气。

代码语言:javascript
复制
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");
}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-14 03:42:17

以下是两种方法:

代码语言:javascript
复制
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文件名从您提供给它的任何源目录构建其文件名数组时。该数组以后可以在后续任务中的任何位置使用。

但是,我建议使用glob和path模块的第二种方法,无论如何,您都应该学习这些方法。第二个方法不需要单独的任务,它只需要在同一个任务中得到、全局、html文件名,这样就更简单了。另外,当我安装gulp文件名时,它使用了大量的废弃模块,因此迫切需要更新。它现在可以工作,但在更新节点时可能不能工作,等等。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49267218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档