简体   繁体   中英

Using Gulp and Gulp Replace Name to clone a project but rename files that contain a certain word inside multiple folders

I need to use gulp to create a clone of a project and change all file types that start with a specific word to have a different word. I have tried using gulp-replace-name.

Below is a simplified example of the folder structure of the project I want to clone. In the real project there are multiple nested folders.

originalProject/
 - readme.txt
 - index.php
 - originalProject.info.php
 - originalProject.setup.php
 - assets/
   - originalProject.css
   - originalProject.js
   - staticAssets.css

And here is an example of the cloned project:

cloneProject/
 - readme.txt
 - index.php
 - cloneProject.info.php
 - cloneProject.setup.php
 - assets/
   - cloneProject.css
   - cloneProject.js
   - staticAssets.css

As you can see, files that start with "originalProject" need to have that text replaced with "cloneProject". You will also notice that there are folders as well as other files which do not need to have their filename changed. Finally, some of the file names contain more than one period in the filename.

Here is the code I created when using gulp-replace-name. This works if there are no folders in the project. When I add folders I get an error.

var gulp = require("gulp");
var changeFilename = require("gulp-replace-name"); 

gulp.task("duplicate", function () {
  return gulp
    .src("./orignalProject/**/*")   
    .pipe(changeFilename(/originalProject/g, "cloneProject"))
    .pipe(gulp.dest("./cloneProject"));
});

gulp.task("default", ["duplicate"]);

This is my first post to stackoverflow. I am also new to gulp. Thank you in advance for any help you can provide.

It's a bug in gulp-replace-name . When it encounters a directory it tries to call a callback cb that doesn't exist, which leads to the error you receive. It also doesn't even attempt to rename directories, which you need.

I suggest you use the gulp-rename plugin instead. It's thoroughly tested and has had a large user base for years, so you're unlikely to run into problems like this.

This a bit more verbose, but does what you want:

var gulp = require('gulp');
var rename = require("gulp-rename");

gulp.task("duplicate", function () {
  return gulp
    .src("./originalProject/**/*")
    .pipe(rename(function(file) {
      file.dirname = file.dirname.replace(/originalProject/g, "cloneProject");
      file.basename = file.basename.replace(/originalProject/g, "cloneProject");
    }))
    .pipe(gulp.dest("./cloneProject"));
});

gulp.task("default", ["duplicate"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM