Recursively Copying Folders with Gulp

How to use Gulp to copy a directory and all of its contents

When building a site or app with Gulp, you often simply need to copy a folder and all of its contents recursively.

Doing it simply is tricky, unless you know this simple incantation:

  • put a * after the folder name (myfolder*)
  • follow that with a /**/* for recursive copy
  • total string is myfolder*/**/*
  • all done

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// recursively copy 'css', 'imgs', and 'fonts' to `dist` directory:

const gulp = require('gulp');

const SRC = 'src/';
const DIST = 'dist/';

function copyFolders () {
return gulp.src([
SRC + 'css*/**/*',
SRC + 'imgs*/**/*',
SRC + 'fonts*/**/*',
])
.pipe(gulp.dest(DIST));
}

exports.default = gulp.series(copyFolders);

The results, displayed here using tree command (another nifty tool):

1
2
3
4
5
6
7
8
9
10
11
dist
├── css
│   ├── overpass-latin.css
│   └── whereami.css
├── fonts
│   └── overpass-latin.woff
├── imgs
│   ├── california-highway-1200x1200.png
│   ├── interstate-sign-1600x1200.png
│   ├── speed-limit-1600x2000.png
│   └── us-highway-sign-1200x1200.png