【问题标题】:Renaming single file names while copying entire folder using copyTpl使用 copyTpl 复制整个文件夹时重命名单个文件名
【发布时间】:2016-08-31 10:50:45
【问题描述】:

我的 yeoman 生成器将文件从模板复制到目标路径:

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

在项目生成期间,我需要将this.props.appName 的值分配给某些文件名。

很遗憾,我不能像在这些文件中那样这样做:

<%=appName%>-project.sln

所有需要重命名的文件的名称中都有appTemplate,所以我需要做的只是将appTemplate 替换为this.props.appName

我能否以某种方式配置 copyTpl 以重命名某些文件,同时将它们复制到另一个目标?

【问题讨论】:

标签: node.js yeoman yeoman-generator


【解决方案1】:

好的,我找到了解决方案。根据yeoman docs

任何生成器作者都可以注册一个 transformStream 来修改文件路径和/或内容。

使用这种方法:

this.registerTransformStream();

这意味着我可以通过一些脚本来管道所有生成的文件:

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
            });
    }
});

此脚本将通过gulp-rename 传递所有文件,将666replacethat666 更改为更智能的东西。

【讨论】:

【解决方案2】:

如果您因为在 Yeoman 中使用 composeWith() 功能(断开转换流注册)而无法使用 registerTransformStream,则可以使用 processDestinationPath,它在您选择多个文件时有效(而不是在您指定出于某种原因,第一个参数中的特定文件)。

this.fs.copyTpl(
  this.templatePath("**/{.*,*}"),
  this.destinationPath(),
  { /* usually your prompt answers are here */ },
  {},
  {
    processDestinationPath: (filePath: string) =>
      filePath.replace(/somedir\/a-file.js/g, 'newdir/better-filename.js'),
  },
);

文档选项的来源:https://yeoman.github.io/generator/actions_fs.html#.copyTemplate

这是基于https://github.com/SBoudrias/mem-fs-editor#copyfrom-to-options-context-templateoptions-

【讨论】:

    【解决方案3】:

    registerTransformStreamgulp-rename 仍然是一个问题。但是,我可以使用 glob。

    const glob = require('glob');
    
    writing() {
        const files = glob.sync('**', { dot: true, nodir: true, cwd: this.templatePath() })
        for (let i in files) {
            this.fs.copyTpl(
                this.templatePath(files[i]),
                this.destinationPath( this.props.destinationFolderPath + '\\' + files[i].replace(/__fileName__/g,this.props.fileName)),
                this.props
            )
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 2014-02-02
      相关资源
      最近更新 更多