返回

Yeoman脚手架进阶:自定义Generator的奥秘

前端

Yeoman Generator简介

Yeoman Generator是Yeoman的核心组件,它允许您创建自己的脚手架,从而自动化项目的创建和配置过程。Generator使用模板系统来生成代码和文件,您可以根据自己的项目需求定制模板。

如何编写一个Generator

要编写一个Generator,您需要创建一个新的Node.js项目并安装Yeoman。然后,您可以使用Yeoman的脚手架命令创建一个新的Generator。

yo yo

这将创建一个名为“my-generator”的新Generator项目。

在“my-generator”项目中,您需要创建一个名为“generators/app/index.js”的文件。此文件包含Generator的逻辑。

// generators/app/index.js
const Generator = require('yeoman-generator');

module.exports = class extends Generator {
  // The name `constructor` is important here
  constructor(args, opts) {
    // Calling the super constructor is important so our generator is correctly set up
    super(args, opts);

    // Next, add your custom code
    this.option('coffee'); // This method adds support for a '--coffee' flag
  }

  initializing() {
    this.log('initializing...');
  }

  prompting() {
    return this.prompt([{
      type: 'input',
      name: 'name',
      message: 'What is the name of your project?'
    }]).then((answers) => {
      this.props = answers;
    });
  }

  writing() {
    this.log('writing files...');

    this.fs.copyTpl(
      this.templatePath('README.md'),
      this.destinationPath('README.md'),
      { title: this.props.name }
    );

    this.fs.copyTpl(
      this.templatePath('package.json'),
      this.destinationPath('package.json'),
      { name: this.props.name }
    );

    if (this.options.coffee) {
      this.fs.copyTpl(
        this.templatePath('app.coffee'),
        this.destinationPath('app.coffee'),
        { name: this.props.name }
      );
    } else {
      this.fs.copyTpl(
        this.templatePath('app.js'),
        this.destinationPath('app.js'),
        { name: this.props.name }
      );
    }
  }

  install() {
    this.log('installing dependencies...');

    this.installDependencies();
  }
};

如何测试一个Generator

要测试一个Generator,您可以使用Yeoman的测试框架。

npm test

这将运行Generator的单元测试。

如何发布一个Generator

要发布一个Generator,您可以使用Yeoman的发布命令。

npm publish

这将把Generator发布到npm。

结语

Yeoman Generator是一种强大的工具,可让您创建自己的脚手架。通过遵循本文中的步骤,您将能够编写、测试和发布自己的Generator。