In Gulp, to copy multiple files while preserving their folder structure, we can use gulp.src to specify the files to copy and gulp.dest to specify the destination folder. Here's a step-by-step guide with examples to achieve this:
1. Installing Gulp
First, ensure that Node.js and npm are installed in your project. Then, install Gulp and the Gulp file operation plugin using npm. Open your terminal or command prompt and run the following commands to install the Gulp CLI and Gulp:
bashnpm install --global gulp-cli npm install --save-dev gulp
2. Creating a Gulp Task
In the project root directory, create a file named gulpfile.js that will contain the Gulp task definitions. Below is a simple task definition for copying files while preserving the folder structure:
javascriptconst gulp = require('gulp'); // Create a task named 'copy-files' gulp.task('copy-files', function () { // `gulp.src` is used to select the files to process; here, the wildcard '**' matches all files, and '!node_modules/**' excludes the node_modules directory return gulp.src(['src/**/*', '!node_modules/**'], { base: 'src' }) // `gulp.dest` is used to specify the output directory .pipe(gulp.dest('dist')); });
In this example, src/**/* selects all files and folders under src, and { base: 'src' } ensures that the files maintain their original folder structure during copying. All selected files will be copied to the dist directory.
3. Running the Gulp Task
In your terminal or command prompt, run the following command to execute the defined copy-files task:
bashgulp copy-files
This command triggers the copy-files task, which copies all files and folders under src (excluding the node_modules directory) to the dist directory while preserving the original folder structure.
Example Explanation
Assume the following file structure:
shell/project /src /images logo.png /scripts app.js index.html
After running the above Gulp task, the dist directory will contain:
shell/dist /images logo.png /scripts app.js index.html
This is a basic example of using Gulp to copy files while preserving folder structure. This method is highly useful for project building and deployment, allowing you to quickly migrate development files to the production directory.