我正在构建一个自定义的yeoman生成器,因此当需要创建文件时,将在我当前位置上方的一个目录或..处创建它们,例如,如果我运行:

yo koala

/home/diegoaguilar/koala中,文件将在/home/diegoaguilar中创建。我应该如何告诉生成器应该在哪里复制文件的路径?我真的以为那是process.cwd()或只是从何处生成yeoman生成器。

这是我生成文件的代码:
  writing: {
    app: function () {
      this.fs.copyTpl(
        this.templatePath('_package.json'),
        this.destinationPath('package.json'),
        {appname: this.appname}
      );
      this.fs.copy(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
    }
  },

最佳答案

首先,我发现使用yeomanthis.template()更加容易,而不是使用来自 this.fs.copy() 所包含实例的this.fs.copyTpl() / mem-fs-editor,但是使用YMMV

无论如何,在尝试编写以确保已设置正确的模板和目标上下文之前,需要在生成器中设置this.sourceRoot('rel/path/to/source/root')this.destinationRoot('rel/path/to/dest/root')See yeoman's getting started guide on interacting with the files system from more informationthis.destinationRoot()应该相对于当前项目的根目录定义(我在下面解释),而this.sourceRoot()应该相对于生成器文件的根目录定义。

您还必须考虑yeoman将尝试找出您当前在命令行中使用的任何应用程序的根目录。它通过向上导航(即/home/diegoaguilar/koala-> /home/diegoaguilar/)直到找到.yo-rc.json文件来完成此操作。然后,Yeoman将最近的.yo-rc.json的目录作为您要在其中运行项目的根目录,将命令运行到该目录。

您可能需要删除/移动/重命名/home/diegoaguilar/.yo-rc.json(如果存在)。然后,您可以创建希望项目驻留在其中的目录,并在其中运行生成器。这看起来像

/home/diegoaguilar/ $> mkdir koala
/home/diegoaguilar/ $> cd koala
/home/diegoaguilar/koala/ $> yo koala

如果您想要或需要将/home/diegoaguilar/.yo-rc.json保留在此处,则应在生成器中相对于this.destinationRoot()设置/home/diegoaguilar/,因此要写入/home/diegoaguilar/koala/,您可以使用this.destinationRoot('koala')

07-24 18:51
查看更多