A little script to generate React components

Ilya Meerovich
2 min readMar 29, 2020
Photo by Anna Jiménez Calaf on Unsplash

Setting up the boilerplate to write a React component can be tedious. On its own, making a directory and putting some files in it with some basic import statements is not a big deal, but doing it over and over (especially when setting up a project) can chip away at your mental resources.

So I wanted to share a little script to help take out some of the legwork.

Assuming the following directory structure:

root
├── scripts
│ └── createComponent.js
├── src
│ ├── components
│ ├── pages
│ └── ...
└── ...

The script affords the following example usage:

$ node scripts/createComponent.js component Header

And yields the following result:

root
├── scripts
│ └── createComponent.js
├── src
│ ├── components
│ │ ├── Header
│ │ ├── __tests__
│ │ │ └── index.test.js
│ │ ├── header.module.css
│ │ └── index.js
│ │
│ │
│ └── pages
└── …

This assumes you’re using CSS Modules, but you can change the file names to suit your setup.

The idea is that presentation components that we might like to generate in the `components` directory can be placed there by specifying `component` in the terminal. Container components to be placed in `pages` can be sent there by using `page` instead.

The script creates the directory with the name you specify, and then for each file that is generated, I have it add some of the imports and boilerplate that I find myself writing most often (React, propTypes, export statement, etc.), but your needs may vary :)

No doubt a more robust version of this could take the form of a full-fledged CLI, with more configuration options, or perhaps a wizard. For now, this little script is already paying for itself.

Here it is in its entirety:

Happy Coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response