如何为自定义 yeoman 生成器文件设置目标路径?

How to setup a destination path for a custom yeoman generator files?

我正在构建一个自定义的 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 最近的目录作为您的项目的预期根目录 运行 命令所在的位置。

在你的情况下,你可能想要 delete/move/rename /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').