gulp zip目录具有不同的基础

时间:2018-05-24 22:23:49

标签: node.js npm gulp build-tools gulp-4

我正在使用gulp 4.我有以下文件结构:

├── gulpfile.js ├── dir1 └── src ├── dir2

我想在同一层中将dir1dir2压缩在一起,即不包括src目录。

我怎么能用gulp做到这一点?

我能想到的一个选项是将不同的任务复制到tmp目录然后用base = tmp压缩它们。但我想找到一个更好的解决方案。

谢谢,

1 个答案:

答案 0 :(得分:0)

您可以使用gulp-rename执行此操作。想法是重命名目录只留下最后一个文件夹。这适用于您的情况因为您只是想要" dir1"和" dir2"但可以通过一些工作来推广。

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

const path = require('path');
const debug = require('gulp-debug');

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

  return gulp.src(['./dir1/*', 'src/dir2/*'], {base: '.'})

    .pipe(rename(function (file) {

      // is there a "/" or "\" (your path.sep) in the dirname?

      let index = file.dirname.indexOf(path.sep.toString());

      if (index != -1) {

        // if there is a folder separator, keep only that part just beyond it
        // so src/dir2 becomes just dir2
        file.dirname = file.dirname.slice(index+1);
      }
    }))

    // just to see the new names (and folder structure) of all the files
    .pipe(debug({ title: 'src' }))

    .pipe(zip('_final.zip'))
    .pipe(gulp.dest('./dist'))
});

注意:我最初尝试使用gulp-flatten,这似乎是一个很好的候选人,但我无法让它工作。

[编辑]:我回去让它与 gulp-flatten 一起使用,这在你的情况下很容易。只需用

替换rename()管道即可
const flatten = require('gulp-flatten');

.pipe(flatten({includeParents: -1 }))

这会将文件夹结构简化为每个文件的路径序列中的最后一个文件夹。