Renaming single file names while copying entire fo

2019-02-20 01:54发布

问题:

My yeoman generator copies files from template to destination path:

this.fs.copyTpl(
            this.templatePath(),
            this.destinationPath(), {
                appName: this.props.appName
            });

During project generation, I need to assign value of this.props.appName to some of filenames.

Unfortunately I can't do this that way like I could do inside this files:

<%=appName%>-project.sln

All files that need to be renamed have appTemplate in their names, so what I need to do is simply replace appTemplate with value of this.props.appName.

Can I somehow configure copyTpl to rename some of files while copying them to another destination?

回答1:

OK, I found a solution. According to yeoman docs:

Any generator author can register a transformStream to modify the file path and/or the content.

Using this method:

this.registerTransformStream();

What that means is I can pipe all generated files through some script:

var rename = require("gulp-rename");
//other dependecies...

module.exports = yeoman.Base.extend({

    //some other things generator do...

    writing: function() {
        var THAT = this;
        this.registerTransformStream(rename(function(path) {
            path.basename = path.basename.replace(/(666replacethat666)/g, THAT.props.appName);
            path.dirname = path.dirname.replace(/(666replacethat666)/g, THAT.props.appName);
        }));
        this.fs.copyTpl(
            this.templatePath(),
            this.destinationPath(), {
                appName: this.props.appName
            });
    }
});

This script will pipe all files through gulp-rename, changing 666replacethat666 to something more intelligent.