How to create your own Yeoman generator

Easy peasy! we just need a package.json file and a index.json where to specify what we want to build and how (interact with the user maybe)

I'm gonna use a very basic example in here however you could go as far as you wish the limit it's your mind :)

First step

Our package.json it should looks like:

package.json

{
    "name": "generator-my-generator-name",
    "version": "0.1.2",
    "description": "My generator description",
    "author": {
        "name": "Israel Sotomayor",
        "url": "http://zot24.com"
    },
    "repository": {
        "type": "git",
        "url": "url-to-my-generator-git-repo"
    },
    "files": [
        "app"
    ],
    "keywords": [
        "yeoman-generator"
    ],
    "dependencies": {
        "chalk": "^1.1.1",
        "yeoman-generator": "^0.20.3",
        "yosay": "^1.1.0"
    }
}

Just have in mind the following key parameters:

  • description
  • keywords
  • my-generator-name

It could worth have a look to the Yeoman's guide lines on How to add your generator guide to add our generator because our package.json have to follow those guide lines.

Second step

In this example I'm gonna just create a folder/files structure so it will be a simple example, we need to add an app folder where we'll and our index.js with the logic that will be excuted as well as a template folder which will contain all the folders/files that will be generated when calling yo.

app  
    index.js
    template
        dummyfile.txt
package.json  

Above our generator structure

index.js

var yeoman = require('yeoman-generator');

module.exports = yeoman.generators.Base.extend({  
  writing: function () {
    this.fs.copy(
      this.templatePath(''),
      this.destinationPath('')
    );
  }
});

The interesting bit on that code is the following:

writing: function () {  
    this.fs.copy(
      this.templatePath(''),
      this.destinationPath('')
    );
  }

That's the logic needed to copy everything on our template folder and generate it, just notice two things:

  • Yeoman it's smart enough to not fuck our possible existing files and it will ask us if we want actually to remplace them or override them along side with other options.

  • Empty folders won't be generated, Yeoman just cares about the files so if you wish to have an empty folder you'll need to add a dummyfile.txt to generate that folder over our new project

And the last step an real example

This is an real example moltin/generator-moltin-service that we are using at moltin to generate our project so we do not start from scratch and everyone will be following the same convention when building new projects.

Notice: if you want to publish your generator you'll need to publish it to npmjs here it's important to remember to follow the name convention generator-my-generator-name so later on yeoman will show our generator on their generator's list.

 Resources