【问题标题】:How to setup a destination path for a custom yeoman generator files?如何为自定义 yeoman 生成器文件设置目标路径?
【发布时间】:2015-11-03 16:31:12
【问题描述】:

我正在构建一个自定义的 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')
      );
    }
  },

【问题讨论】:

    标签: javascript yeoman yeoman-generator


    【解决方案1】:

    首先,我发现使用yeomanthis.template() 比使用来自mem-fs-editor 包含的实例的this.fs.copy()/this.fs.copyTpl() 更容易,但是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')

    【讨论】:

    • @diegoaguilar 在其他地方问我为什么更喜欢this.template(),所以我想我也会在这里包括答案:this.template() 的主要优点是你可以用它来代替@ 987654346@ 和this.fs.copyTpl(),它默认提供当前生成器实例(即this)作为模板上下文。如果您的文件是没有要模板化的ejs 标签的直接副本,那么是否提供this 并不重要; mem-fs-editor 会正确处理。
    • 这可能是一个问题的唯一地方是,如果您想执行this.fs.copy() 并将进程选项传递给mem-fs-editor,如this answer on another question 中所述。在深入研究之后,我看到copyTpl() 函数不允许像copy() 这样的process 函数,因为copyTpl() 本身实际上调用了copy(),并且它本身已经传递了一个调用ejs.render() 的函数process 选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    相关资源
    最近更新 更多