Skip to content

Code Generators

When building an application it's common to have repeating patterns of code. One approach I used to use I call "copy, paste and gut". I end up copying existing code and ripping out the parts I don't need. It's crude. It works. Until it doesn't. This approach is prone to introducing bugs from code I "forgot" to gut out. There is a better way....enter code generation with Hygen.

Imagine each time you need to make a UI component. Let's assume you have to create:

  • the component file
  • the test spec file
  • the story file (your're using storybook)
  • markdown files for documentation

More than likely there is common elements and structure to these files that you have to maintain which can only be done manually the conventional way. With Hygen you can easily define the base templates for all these files. Then, with one command, generate a scoffold of your component. Now you can get to work faster.

Code generation saves you time and produces more consistent code.

Included Generators

StarterStack comes with 3 generators to get you started:

  • middleware-generator: generates the starting scaffold of a route middleware method
  • email-generator: generates the starting scaffold of an express-handlebar email template
  • component-generator: generates the starting scaffold for a Vue component

Generating Code

The command is simple. The format looks like this:

sh
hygen {the name of your generator} new {the name of what your generating }

For example, let's say we want to generate a new email template to contact users that have not visted our site in a long time. We'll call it "We-Miss-You"

sh
cd /backend
hygen email-generator new We-Miss-You

This command will generate the following scaffold email located at /backend/mail/we-miss-you.handlebars

Create Your Own Generator

It's super easy to create your own custom code generators with Hygen. Let's look at the command.

WARNING

Make sure you are in /frontend if you want to generate frontend code and /backend for backend code

sh
cd /frontend
hygen generator new {the name of your generator}

For example:

sh
cd /frontend
hygen generator new vue-component-generator

This will create the necessary files to start building out your generator templates. You will find these located in /backend/_templates/vue-component-generator.

For more details on creating the actual code generation templates please read the Hygen docs