Scaffolding Repetitive Code With Hygen

Manual file scaffolding is one of those chores that eats time across a project. In a Next.js app, new components often require a folder plus several files — a component, a test, a stylesheet, maybe a story. Recreating that structure by hand is tedious and error prone, especially when muscle memory makes you create a file instead of a folder.

Hygen is a CLI tool that automates this process. It scaffolds out templates that live in your repository, which means the templates are version-controlled and shared across the team. Everyone uses the same structure and they can be updated in code review like any other file.

Setting up the tool follows the recommended global install procedure:

npm i -g hygen

The author notes some uncertainty about whether a global install is the right approach versus a local one for ensuring team-wide consistency, since a global install can be forgotten or missed by new contributors.

To generate a new component, the command points at a template directory. The CLI looks in the nearest _templates folder and runs everything it finds there:

hygen editor-component new --name NewExampleComponent

The template directory contains files whose names don't strictly matter, because Hygen reads their front matter to determine where the generated file lands and what it's called. That means file paths and names can be templated just like content.

Hygen's templating syntax is reminiscent of Rails ERB. A flag like --name Cool makes the value available as <%= name %>, and helpers exist for transforms like upper or lowercase.

Running the command drops the files into place:

Notes

  • The team structure for a component in this project looks like:
/NewComponent
  index.js
  NewComponent.js
  NewComponent.module.scss
  • Alternatives like Plop exist, but Hygen's syntax andapproach were a better fit for this author.
  • The author would appreciate something like a hygen jk rollback command for removing a scaffolded set of files after a misspelling or other mistake.
  • A VS Code extension lets you trigger scaffolding from the Command Palette, avoiding a trip to the terminal to recall commands.