How to copy multiple files and keep the folder structure with Gulp

JavascriptCssGulp

Javascript Problem Overview


I am trying to copy files from one folder to another folder using Gulp:

gulp.task('move-css',function(){
  return gulp.src([
    './source/css/one.css',
    './source/other/css/two.css'

    ]).pipe(gulp.dest('./public/assets/css/'));
});

The above code is copying one.css & two.css to the public/assets/css folder.

And if I use gulp.src('./source/css/*.css') it will copy all CSS files to the public/assets/css folder which is not what I want.

How do I select multiple files and keep the folder structure?

Javascript Solutions


Solution 1 - Javascript

To achieve this please specify base.

>¶ base - Specify the folder relative to the cwd. Default is where the glob begins. This is used to determine the file names when saving in .dest()


In your case it would be:

gulp.task('move-css',function(){
  return gulp.src([
      './source/css/one.css',
      './source/other/css/two.css'
  ],  {base: './source/'}) 
  .pipe(gulp.dest('./public/assets/'));
});

Folder structure:

.
├── gulpfile.js
├── source
│   ├── css
│   └── other
│       └── css
└── public
    └── assets

Solution 2 - Javascript

I use gulp-flatten and use this configuration:

var gulp = require('gulp'),
    gulpFlatten = require('gulp-flatten');

var routeSources = {
  dist:  './public/',
  app: './app/',
  html_views: {
    path: 'app/views/**/*.*',
    dist: 'public/views/'
  }
};

gulp.task('copy-html-views', task_Copy_html_views);
function task_Copy_html_views() {
  return gulp.src([routeSources.html_views.path])
      .pipe(gulpFlatten({ includeParents: 1 }))
      .pipe(gulp.dest(routeSources.html_views.dist));
}

And there you can see the documentation about gulp-flatten: Link

Solution 3 - Javascript

   gulp.task('move-css',function(){
      return gulp
                  .src([ 'source/**'], { base: './' })
                  .pipe(gulp.dest('./public/assets/css/'));
    });

Your own code didn't include the entire dir tree of source 'source/**' and the base {base:'./'} when calling to gulp.src which caused the function to fail. The other parts where fine.

gulp.task('move-css',function(){
  return gulp.src([
    './source/css/one.css',
    './source/other/css/two.css'

    ]).pipe(gulp.dest('./public/assets/css/'));
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNullPoiиteяView Question on Stackoverflow
Solution 1 - JavascriptAnulal SView Answer on Stackoverflow
Solution 2 - JavascriptJulian Alejandro SosaView Answer on Stackoverflow
Solution 3 - JavascriptKingsolo50View Answer on Stackoverflow