Genponent - a React component generator written in Go
After a while of working with React, you'll start to notice that creating new components always requires the same sort of boilerplate code.
A new folder, a file for your component, a style file... Props, if you're using TS.
And where repetitive actions that need doing on your computer can be found, so can an opportunity to automate it.
https://github.com/BruceJi7/genponent
This is genponent. It generates components for React. Apparently this is quite like something Angular can do!
Originally I whipped up a quick program that only accepted one argument - the component name - and produced the component folder.
More recently, I dug into Go's flag library, and filled genponent out with optional features.
It turns out the flag library makes setting up flags very easy:
var javascriptFlag = flag.Bool("j", false, "Generate a JavaScript component instead of TypeScript")
var cssFlag = flag.Bool("c", false, "Generate a component with CSS instead of SCSS")
var noStyleFlag = flag.Bool("s", false, "Generate a component with no style")
var noPropsFlag = flag.Bool("p", false, "Generate a component without a Props declaration")
By filling out these variable declarations, and including a usage string, you're actually also setting up the --help flag.
It also makes getting the rest of the args easy:
remainingArgs := flag.Args()
Even better, really, since system arguments like this are always parsed into an array, so that makes getting genponent to generate multiple components very easy!
Most recently, I refactored it to generate what I found out is called a 'barrel file'. Now, when you use genponent, with component name $name, you receive:
- A folder called $name,
- A file called $name, containing a React functional component called $name,
- A sass file, $name.module.scss,
- An index file, importing the component and exporting it as default.
The React component will look like this:
import React from "react";
import styles from "./$name.module.scss";
interface Props {}
function $name({}: Props) {
return <div className={styles.$name}></div>;
}
export default $name;
...with the matching class name in the sass file.
And options available are: -c using css, -j using javascript, -s using no style, and -p using no props.
For the time being, if you want to use it, you'll have to clone it and build it yourself. I will be adding built versions soon!
You'll want to add genponent to your PATH global variable, and if you're using linux or mac, you'll want to run sudo chmod +x genponent so it's executable.
Hope it's useful for you!
Still here? Wondering why I used Go? It's a very good point. I really like Go, so I wanted to make this in Go to get more practice. It would definitely suit being an NPM package... Maybe another time!
