gulp zip directories with different bases

567 Views Asked by At

I'm using gulp 4. I have the following file structure:

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

I want to zip dir1 and dir2 together in the same layer, i.e. not including src directory.

How can I do it with gulp?

One option I can think of is having to different tasks to copy them to a tmp directory then zip them with the base = tmp. But I want to find a better solution.

Thanks,

1

There are 1 best solutions below

0
On

You can do it using gulp-rename. The idea being to rename your directories to leave only the last folder. This works in your case since your just want "dir1" and "dir2" but could be generalized with some work.

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'))
});

Note: I originally tried using gulp-flatten which seems like a good candidate for this, but I couldn't get it to work.

[Edit]: I went back to get it to work with gulp-flatten and it is very easy in your case. Just replace the rename() pipe with

const flatten = require('gulp-flatten');

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

That will reduce the folder structure to just the last folder in each file's path sequence.