Using hygen.io (a code generator) at Infraspeak

Ana Basílio
infraspeak
Published in
8 min readOct 11, 2022

Why use a code generator?

As Infraspeak’s engineering team grew exponentially, some issues started to emerge. We needed to set rigid guidelines on how we should build components, write functions and organize file logic so that our codebase could grow sustainably with the team. Whilst guideline documentation was good, it was very easy to enter “development mode” and forget to apply them. Only later in the code review phase would we spot and fix problems. Equally, repetitive tasks which had to be done were also a major pain point.

We needed a solution that could add automation to some of these processes. After some digging around, we discovered code generators.

Code generators focus on automating repetitive tasks by creating structured templates with standard code that can be repeated in your codebase. This works because when a page, component, or utility function needs to be built, there’s usually something similar already implemented.

At Infraspeak we use a code generator named hygen.io. This library allows us to add multiple template files, inject code into existing ones, get prompts for user activity, and more. With these new features our developers could:

  • Exponentially reduce the need for copy and paste;
  • Ensure that everyone is doing things “the right way”;
  • Facilitate code review;
  • Simplify the onboarding of new developers;
  • Speed up the development process.

The above points are very important when working in a large team, where everyone has their own coding style; new members keep joining your team, and technology specs continuously grow.

Now that we’ve had a glimpse at what code generators can do for us, let’s understand how hygen works.

Code generation path (with Vue)

In this section, we’ll provide a step-by-step analysis of how you can use the hygen library to generate a premeditated Vue file. At Infraspeak, we work with Vue and TypeScript. Any generated file must therefore be built according to this framework and typed programming language (learn more about why Infraspeak chose to use TypeScript). We use this code generator library for a large number of specifications and features, but we will focus only on some of the most used ones at Infraspeak.

This example will consist of two parts: first, the construction of a hygen template (implementing the logic), and after this step follows the generation of the result (creating the Vue.js file)

As a prerequisite, you need the hygen generator running on your project.

The construction

Hygen extensibility

In the setup phase, it’s important to know that the code generator library provides a configuration file named hygen.js whose function is to allow the creation of an extensibility point. This is a special file searched and loaded by a bubbling engine implemented by hygen. The search process runs when the command is triggered and stops at the first file found.

File traits:

  • Helper functions in templates;
  • Customizing logger, template location, and shell executor.

The previous image represents the extensibility we intend to give to our templates for this example. The first templates section defines the location where the hygen templates are created and the helper’s section defines the root path which shows where to generate the new file. The hygen search engine will now run your templates using the path defined in the templates section and the root path is now the one defined in the helper’s section.

Hygen template

Hygen templates are created with the help of an EJS (Embedded JavaScript) engine, which allows you to embed JavaScript within the HTML code. An EJS template normally contains mostly static elements that are responsible for giving a file a certain structure.

You can also add dynamic elements that can be settled with data from an external source, such as prompts which will be analyzed later.

This type of template is defined by a header using a markdown Front-matter and a body using an EJS templating engine.

  • Header: The header section is used to guide the code generator on what should happen and how it will be done;
  • Template body: The template body defines what the generated file will contain.

Prompt definition

The hygen library makes it possible to build a CLI wizard which is essential for customizing the logic added to the templates. You can apply user-defined variables, add conditions, and also implement dynamic naming. With these prompt specifications, you can create an interactive code-generation experience.

The image below shows the prompt that will be executed in this example. As represented in the image, an input interaction is implemented in the prompt, where the intervener must enter a message of his choice.

Note that the template file uses the inserted message as a local variable to add a comment. That’s possible because any CLI argument or prompt parameter automatically becomes a local variable in your templates.

Conditioning the template with some logic that is only implemented when a certain conditional statement verifies can also be useful. As represented in the previous image, the comment message is only implemented if the message to be commented on is defined.

It’s also important to highlight that when executing the hygen code generation command, you will need to define a name for the generating file. This name is also included in the header and body sections of the template logic. Also, the file and class names are defined according to that command parameter.

Code injections

On some occasions, you might want to add code snippets to an existing file. For that, the hygen library has something called injections. To implement an injection you need to add the inject property to the template and specify the file where you want to implement that code. Keep in mind that the position specification (after: “//Inject console log”) needs to match with the one defined on the receiving file.

Generating Results

How it works

The purpose of these configurations is to generate a file that will be built according to the EJS template logic. With this automation, we will be able to create a Vue.js file not from scratch, but with the logic already built-in on the defined template itself.

Let’s jump to the final steps of our Vue.js file generation and run the command that will make our code generator work.

To understand how the generating command is built, it’s necessary to look at the hygen templates directory tree.

Note that the files should be sorted correctly. Looking at this injection case example, if you place your injection file before your component file the injection wouldn’t work. You can use numbers in your filenames or order them the way you want hygen to process your logic.

Moving on to the command to generate the Vue.js file, it will consist of three main parameters:

  • demo: Hygen root directory name;
  • hygen-test: The directory that contains the templates to run;
  • Example: The name of the file to be generated.

When running the command, the prompt steps in and requests the comment message. After the message input is inserted, the console logs information stating that it created a new file named Example.vue and also that some code was injected into that file.

Now let’s finish this example with a review of the successful content generated following the execution of this command.

As you can see above, a new file has been generated and follows the implemented EJS logic.

With the help of the defined prompt, it was possible to insert the file name to be generated, which comment to write, and dynamically inject the console log message. The header section of the EJS template was also responsible for managing the path where the new Vue.js file would be generated.

Conclusion and thoughts

This code generator library can provide your codebase with a more controlled development environment and also helps us to follow the DRY (Don’t Repeat Yourself) principle smartly. There are, of course, some unavoidable, repetitive steps and processes in our workflow that need manual solutions. However, there’s no need for developers to have to write everything over and over again. This is the main purpose of code generators.

As well to the previously discussed advantages, a code generator can also:

  • Help to flatten the learning curve of a big project;
  • Bring more independence to developers;
  • Make use of these hygen templates in a very easy way;
  • Comment-oriented templates can lead to a more documented code;
  • Generating tests automatically with some built-in logic already integrated can be the right trigger to encourage test implementation.

It’s also worth considering the other side of the coin.

When analyzing any type of library, it’s important to understand the challenges you might face when integrating the tool into your codebase. Here are some downsides related to the usage of this code generator:

  • The language used to build the logic of the templates is hard to understand at first;
  • As you build more extended templates, hygen will become more complex;
  • When working on a project where updates and changes are constant, it’s normal for the templates to be outdated. The downside comes when updating templates requires manual intervention and is not an automated process.

As illustrated, code generators can have a positive impact on your development process when used and maintained correctly. It’s an investment your team should consider when you find yourself repeating the same scaffolding procedures over and over again. Have you given it some thought? Which code generator did you go for?

--

--