• Stars
    star
    5,610
  • Rank 7,278 (Top 0.2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The simple, fast, and scalable code generator that lives in your project.

hygen logo

build status npm version

hygen is the simple, fast, and scalable code generator that lives in your project.

Features

  • βœ… Build ad-hoc generators quickly and full on project scaffolds.
  • βœ… Local generators per project (and global, if you must)
  • βœ… Built-in scaffolds to quickly create generators
  • βœ… Full logic templates and rendering
  • βœ… Prompts and flows for taking in arguments
  • βœ… Automatic CLI arguments
  • βœ… Adding new files
  • βœ… Injecting into existing files
  • βœ… Running shell commands
  • βœ… Super fast, constantly optimized for speed

New in hygen v4.0.0: a positional NAME parameter. Now you can use $ hygen component new MyComponent instead of $ hygen component new --name MyComponent.

Used By

Wix Β  Β  Airbnb Β  Β  Mercedes Benz AG Β  Β  Open Data Institute Β  Β  Ableneo Β  City of Amsterdam Β  Β  Accenture Β  Birdie Β  Β  Kind Β  Β  Ackee Β  Aerian Studios Β Food and Agriculture Organization of the UN Cape Cod Commision Β  Tweak Things Β  Β  Crema Β  Β  Cureon Β  Β  Astrocoders Β  Β  Vega/IDL Β  Sporty Spots Β  Β Thrashplay Β Β 8base Β Β  Instamotionh Biotope Frontend Labs Swydo Gridsome Rosem LaboratorySheffield Hallam University Hackoregon Chilly Design

Scale Leap

Chat Logs

Stelace

Echobind.

Quick Start

Hygen can be used to supercharge your workflow with Redux, React Native, Express and more, by allowing you avoid manual work and generate, add, inject and perform custom operations on your codebase.

If you're on macOS and have Homebrew:

$ brew tap jondot/tap
$ brew install hygen

If you have node.js installed, you can install globally with npm (or Yarn):

$ npm i -g hygen

If you like a no-strings-attached approach, you can use npx without installing globally:

$ npx hygen ...

For other platforms, see releases.

Initialize hygen in your project (do this once per project):

$ cd your-project
$ hygen init self

Build your first generator, called mygen:

$ hygen generator new mygen

Loaded templates: _templates
       added: _templates/mygen/new/hello.ejs.t

Now you can use it:

$ hygen mygen new

Loaded templates: _templates
       added: app/hello.js

You've generated content into the current working directory in app/. To see how the generator is built, look at _templates (which you should check-in to your project from now on, by the way).

You can build a generator that uses an interactive prompt to fill in a variable:

$ hygen generator with-prompt mygen

Loaded templates: _templates
       added: _templates/mygen/with-prompt/hello.ejs.t
       added: _templates/mygen/with-prompt/prompt.js

Done! Now let's use mygen:

$ hygen mygen with-prompt
? What's your message? hello

Loaded templates: _templates
       added: app/hello.js

Use a template repo

Want to start from a repo?

$ hygen init repo antfu/vitesse --to my-folder

Want to start from an existing repo on an existing project?

$ mkdir your-project && cd your-project
$ hygen init repo antfu/vitesse

What's Next?

Go to the documentation to get to know the rest of Hygen and generators.

If you're in a hurry:

  • To learn how to edit generator templates, look here
  • To see how to use generators look here
  • Take a look at the ecosystem and tooling built around Hygen.

A Different Kind of a Generator

hygen is a scalable generator. It has developer and team ergonomics as first priority.

It avoids "blessed" or dedicated projects that codifies code generation, which before you know it, become a product you build, needs testing, CI, separate pull request reviews, and ultimately sucks up your time and becomes this super hated thing no one likes to touch anymore.

Plus, since they are not the product you are building they become notoriously hard to reason about.

Scratch Your Own Itch

Because hygen templates live in your project, it cuts the time from having an itch for generating code (Redux, anyone?) in your current project to code generated with it and others benefiting from it.

Template Locality

hygen picks up a local _templates folder at any folder level of your project you're working from.

This is important because:

  • Templates are project-local. A git clone of the project fetches all generators as well.
  • Different generators can be tucked in different parts of the project, making it contextual.
  • Template locality is scalable; different teams can maintain different generators.
  • When you change your code, you can make changes in the template and pack in the same commit, to be reviewed and merged in the same PR (as opposed to installing different "plugins" or different templates from out-of-repo places).

And yet, if you don't like project-local templates:

  • You can have a global _templates folder (maybe a central git repo you maintain?) by populating an environment variable HYGEN_TMPLS
  • You can build a custom generator of your own with hygen at its core, and pack your own templates with it.

Folder Structure is Command Structure

The templates folder structure maps directly to the command structure:

$ hygen worker new jobrunner

For this command, hygen worker new maps to _templates/worker/new and all files within worker/new are rendered.

Template parameters are given with --flag VALUE, as many as you'd like. In this example we've set a parameter named name to the value jobrunner.

Subcommands

A subcommand is a file inside a your folder structure. So if the structure is this:

_templates/
    worker/
      new/
        index.html.ejs
        setup.html.ejs

And you only want setup, you can run:

$ hygen worker new:setup

You can also use the subcommand as a regular expression so, these will do the same:

$ hygen worker new:se
$ hygen worker new:se.*

Frontmatter for Decluttering

Here's how a template looks like (in our example, index.ejs.t). Templates bodies are ejs:

---
to: app/workers/<%=name%>.js
---

class <%= h.capitalize(name) %> {
    work(){
        // your code here!
    }
}

The first part of the template is a front matter, idea borrowed from Markdown, this is the metadata part of a hygen template and is part of the reason of why your templates will feel more lightweight and flexible.

All frontmatter metadata are also run through the template engine so feel free to use variables in the frontmatter as you wish.

There's one required metadata variable: to. to points to where this file will be placed (folders are created as needed).

Case changing

hygen provides ability to semantic case changing with change-case library, it's simple to use and very easy to understand.

There is a usecase for react based components generation:

---
to: components/<%= name %>/index.jsx
---
import React from 'react'

export const <%= name %> = ({ children }) => (
  <div className="<%= h.changeCase.paramCase(name) %>">{children}</div>"
)

With name HelloWorld will be compiled to:

import React from 'react'

export const HelloWorld = ({ children }) => (
  <div className="hello-world">{children}</div>"
)

You can see the full list here.

Addition, Injection, and More

By default templates are 'added' to your project as a new target file, but you can also choose to inject a template into an existing target file.

For this to work, you need to use inject: true with the accompanied inject-specific props.

---
to: package.json
inject: true
after: dependencies
skip_if: react-native-fs
---
"react-native-fs":"*",

This template will add the react-native-fs dependency into a package.json file, but it will not add it twice (see skip_if).

Here are the available mutually-exclusive options for where to inject at:

  • before | after - a regular expression / text to locate. The inject line will appear before or after the located line.
  • prepend | append - add a line to start or end of file respectively.
  • line_at - add a line at this exact line number.

You can guard against double injection:

  • skip_if - a regular expression / text. If exists injection is skipped.

Also you can insert or remove empty line to injection body. That feature very useful if your editor or formatter automatically insert blank line at the end of file on save:

  • eof_last - if falsy - trim blank line from the end of injection body, if truthy - insert it.

Build Your Own

hygen is highly embeddable. You should be able to use it by simply listing it as a dependency and having this kind of workflow in your binary.

const { runner } = require('hygen')
const Logger = require('hygen/dist/logger')
const path = require('path')
const defaultTemplates = path.join(__dirname, 'templates')

runner(process.argv.slice(2), {
  templates: defaultTemplates,
  cwd: process.cwd(),
  logger: new Logger.default(console.log.bind(console)),
  createPrompter: () => require('enquirer'),
  exec: (action, body) => {
    const opts = body && body.length > 0 ? { input: body } : {}
    return require('execa').shell(action, opts)
  },
  debug: !!process.env.DEBUG
})

Development

The Hygen codebase has a functional style where possible. This is because naturally, it feeds parameters and spits out files. Try to keep it that way.

Running hygen locally, rigged to your current codebase (note the additional -- to allow passing flags)

$ yarn hygen -- mailer new foobar

Running tests in watch mode:

$ yarn watch

Metaverse Testing

The easiest way to make an impact is to use the built-in metaverse tests suite, and then add the tests here.

The idea here is to copy templates from any project that use hygen and to test that it works at all times. This keeps tabs on the hygen universe / ecosystem (nicknamed metaverse) and makes sure this test suite breaks before hygen clients break.

Internal Testing

Start Up Speed Testing

Many generators become painfully slow to use as the thing you want to generate grow (because, real life),

This is why hygen takes speed as a first class citizen, and sports a dedicated start-up timing suite:

$ yarn test:require

In addition, thought is given to which dependencies to take in, how their file structure fan out and what kind of disk access (due to require) would hygen ultimately have when we run it. This is recorded with every test run.

Bundling a single file was evaluated (and the infrastructure is still there, using webpack) and wasn't faster than what we have right now.

Contributing

Fork, implement, add tests, pull request, get my everlasting thanks and a respectable place here :).

Thanks:

To all Contributors - you make this happen, thanks!

Copyright

Copyright (c) 2018 Dotan Nahum @jondot. See LICENSE for further details.

More Repositories

1

awesome-react-native

Awesome React Native components, news, tools, and learning material!
JavaScript
33,342
star
2

graphene

Graphene is a realtime dashboard & graphing toolkit based on D3 and Backbone.
CSS
2,881
star
3

react-flight

The best way to build animation compositions for React.
JavaScript
2,825
star
4

awesome-devenv

A curated list of awesome tools, resources and workflow tips making an awesome development environment.
2,622
star
5

sneakers

A fast background processing framework for Ruby and RabbitMQ
Ruby
2,246
star
6

goweight

A tool to analyze and troubleshoot a Go binary size.
Go
1,687
star
7

rust-how-do-i-start

Hand curated advice and pointers for getting started with Rust
1,055
star
8

ReactNativeKatas

This is a project that lets you participate in a fully-immersive, hands-on, and fun learning experience for React Native.
JavaScript
947
star
9

awesome-weekly

An "awesome" type curated list of quality weekly subscription newsletters from the software world
890
star
10

blade

Better asset workflow for iOS developers. Generate Xcode image catalogs for iOS / OSX app icons, universal images, and more.
Go
818
star
11

groundcontrol

Manage and monitor your Raspberry Pi with ease
Go
769
star
12

rn-snoopy

Snoopy is a profiling tool for React Native, that lets you snoop on the React Native Bridge.
JavaScript
523
star
13

react-native-slowlog

A high-performance timer based profiler for React Native that helps you track big performance problems.
JavaScript
374
star
14

awesome-rust-llm

πŸ¦€ A curated list of Rust tools, libraries, and frameworks for working with LLMs, GPT, AI
220
star
15

crunch

A fast to develop, fast to run, Go based toolkit for ETL and feature extraction on Hadoop.
Go
210
star
16

moxy

The programmable mock proxy
Ruby
120
star
17

webnull

web/null eats your HTTP
CoffeeScript
104
star
18

padrino-warden

A Padrino module that provides authentication for your Padrino application through Warden
Ruby
100
star
19

tauri-tray-app

A Tauri tray app starter πŸ¦€
TypeScript
94
star
20

roundtrip

Simple tracking and metrics for your business processes in real-time
Ruby
89
star
21

awesome-aha

Awesome list for "Aha!" moments related to programming and computer science. Accelerate your learning.
82
star
22

nina

The friendly web microframework that performs!. Nina is a feature complete web microframework for the .Net platform, inspired by Sinatra
C#
70
star
23

frenzy_bunnies

RabbitMQ JRuby based worker framework on top of march_hare (hot_bunnies)
Ruby
70
star
24

redux-stack

Redux Stack is a library that helps you build modular, structured, and cleaner redux apps
JavaScript
67
star
25

storybook-cartesian

Automatically generate stories for all of your component variants
TypeScript
63
star
26

vitals

Flexible StatsD instrumentation for Rails, Rack, Grape and more
Ruby
51
star
27

version_bumper

Bump your versions
Ruby
47
star
28

logbook

Log your memories onto virtual logbooks made of Gists
Ruby
43
star
29

mediumize

Automatically post (and cross-post) your markdown style blog posts to your Medium account from Jekyll, Middleman, Hugo and others.
Ruby
40
star
30

nchurn

.Net based churn analyzer for your build
C#
37
star
31

awesome-designops

Awesome DesignOps is an awesome style list that curates the best design ops news, tools, tutorials, articles and more.
JavaScript
37
star
32

scatter

Ruby
35
star
33

benchmark-ipsa

An iterations per second enhancement to Benchmark that includes memory allocations
Ruby
32
star
34

go-cli-starter

A Go based command line interface starter app (CLI)
Go
32
star
35

fattyproject

Go
32
star
36

react-native-network-boot

An alternative way of bootstrapping development network bundling for React Native
JavaScript
31
star
37

awesome-beginners

A list that curates resources to help you teach your kids, wives, husbands, family or friends how to code
29
star
38

gulpjs-phaser

CSS
29
star
39

xtaskops

Goodies for working with the xtask concept in Rust
Rust
29
star
40

PrimerApp

JavaScript
25
star
41

groundcontrol-ui

JavaScript
25
star
42

attrs-serde

A serialization addon for attrs.
Python
24
star
43

passage

Personal, tiny, flexible, OpenID provider
Ruby
22
star
44

pgpipeline

A Scrapy pipeline module to persist items to a postgres table automatically.
Python
21
star
45

hygen-CRA

Perl 6
21
star
46

redux-duet

Redux action and handlers together, alleviate boilerplate.
JavaScript
20
star
47

langchain-llm-katas

This is a an open-source project designed to help you improve your skills with AI engineering using LLMs and the langchain library
Python
18
star
48

vscode-hygen

This extension bundles Hygen into VSCode and offers seamless code generator functionality right into your editor.
TypeScript
18
star
49

pcwr

Pragmatic Concurrency With Ruby
Ruby
17
star
50

castbox

A chromecast 1.0 emulator
Go
17
star
51

formation

A generic functional middleware infrastructure for Python.
Python
17
star
52

elb-dash

A self-updating ELB status board / dashboard built with React, Coffeescript and Node.js.
CoffeeScript
16
star
53

make-vscode-more-like-vim

Make VSCode more like vim
15
star
54

qtools

qtools are a set of tools to greatly ease your MSMQ operations, monitoring and deployment
C#
15
star
55

hygen-add

hygen-add is one of the tools in the Hygen toolbelt which allows you to add pre-made generator packages to your project.
JavaScript
14
star
56

deep-learning-parameters-cheatsheet

14
star
57

elasticsearch-balance

Visualize the data distribution of your Elastic Search cluster using a Treemap
JavaScript
13
star
58

darkness

JRuby with Swing WriteRoom/Darkroom-like editor.
Java
13
star
59

heatmapdotnet

Heatmap generator for .Net
C#
13
star
60

blade-sample

Swift
13
star
61

rawsort

A simple but powerful RAW photo import tool built to have amazing performance and integrate with photography workflows.
Rust
13
star
62

hypermatch

A fast, sandboxed micro matching engine with serializable rules.
JavaScript
12
star
63

cottonballs

Your own mock, fluffy version of GCM for testing purposes
CoffeeScript
12
star
64

packs

An open-source BoxJS/CSS/Etc clone, suitable for hosting at Heroku
JavaScript
12
star
65

rrgen

Rust
11
star
66

10bisbar

A bitbar plugin that helps you do the math for your 10bis account
Go
11
star
67

primer-bind

Go
11
star
68

dg

Check a folder for dirty git repositories, forgotten branches and commits
Rust
11
star
69

lidar

A take on ThoughtWorks' Radar. You can use this tool and system to make your very own technological Radar.
JavaScript
11
star
70

statsd-stack

A statsd Sprinkle stack
Ruby
11
star
71

react-rust-chrome-starter

Chrome extension template with Rust πŸ¦€ and React using Vite and tailwind
TypeScript
11
star
72

celeste

An all-in-one tool for the repository maintainer.
JavaScript
10
star
73

statsd-cli

Simple Statsd command line interface
Ruby
10
star
74

jill

Jill is your README.md assistant
Ruby
10
star
75

dazzling

Dazzling is a project website generator based on Gatsby and React that's simple, quick, and extensible.
JavaScript
10
star
76

logolang.org

Retro LOGO with a modern twist. Built with Rust+WASM πŸ¦€
TypeScript
10
star
77

firebase-simple-storage

An unofficial Go based client for Firebase storage that preserves security (goes through Firebase and not Google Cloud Storage).
Go
10
star
78

signup

Easy and lightweight signup service
Go
9
star
79

keymaps

Shell
9
star
80

gravy

Sweet sauce for your Gravatars: realtime gravatar manipulation with Node.JS
9
star
81

autobrew

Automate homebrew formula publishing for your CLI tools, regardless of programming language.
Go
9
star
82

webogram

Snap your web pages through Instagram inspired filters. You can use this to generate wallpapers for phone and desktop, icons, and book covers
JavaScript
9
star
83

goddamn-javascript-babel

A zero config package that gives you a bleeding edge Javascript, with the latest proposals including pipe operator foo |> bar, optional chaining foo?.bar, null coalescing foo ?? bar and more.
JavaScript
9
star
84

arper

A network utility and library for discovering network device via ARP scans, including vendor names.
Go
8
star
85

react-native-fs-walker

A React Native file system walker and file tree debugging tool
JavaScript
8
star
86

hypercontroller

A more civilized controller abstraction for TypeScript and Node.js. Hosts libraries for controllers built using hypergen
TypeScript
8
star
87

es-diag

Elastic Search health checks and problem discovery toolkit
Ruby
8
star
88

pocket-emails

A compact tool that sends digest emails from your Pocket account with Mailgun.
JavaScript
8
star
89

dash

Communicate to the mass with Dash on your TV/LCD/Plasma
JavaScript
8
star
90

armor

WIP - a pragmatic Go microservice framwork
Go
8
star
91

react-native-bundles

Hand-picked bundles of React Native libraries and components that go well together for any kind of app
8
star
92

react-redux-classconnect

JavaScript
7
star
93

react-native-group-image

A <GroupImage /> component for React Native. A group image will be responsive towards the amount of images it needs to display
JavaScript
7
star
94

serverless-zen

A serverless starter project focusing on uncompromising local development experience without serverless fatigue.
TypeScript
7
star
95

dotlinker

Use dotrunner and dotlinker to build a fantastically aesthetic macOS dotfiles set up.
Python
7
star
96

dotfiles

configuration files.
Vim Script
7
star
97

outpostapp

Flexible file upload app
JavaScript
7
star
98

appium-solo

Appium simplified: Run E2E tests with a dedicated appium instance per device.
JavaScript
6
star
99

stylomatic

Zero configuration for typescript, react, and more
JavaScript
6
star
100

mongomon

A Python mongodb monitor and profiler for development.
Python
6
star