DEV Community

Cover image for Automating React Component Generation with a Shell Script
Sara
Sara

Posted on • Updated on

Automating React Component Generation with a Shell Script

React components are the building blocks of a React application. Creating them manually can be time-consuming, especially when they follow a similar structure. In this blog post, we'll explore how to automate the process of generating React components using a shell script. We'll build a script that takes a predefined template and creates components with custom names and file structure.
*This example is only for Linux or MacOS

Prerequisites

Before we begin, ensure that you have the following set up:

  1. A working shell environment (e.g., Bash).
  2. Node.js and npm installed on your machine.

Create a folder named template and create three files: index.js, component.css and interfaces.d.ts (if you're using typescript). If you are using scss or any other styling, create the style file according to your needs.

Step 1: Setting up the Template

First, let's set up a template file that represents the structure and content of a React component. For this simple example, we'll create a simple component that uses css for styling.

// index.js

const COMPONENT_NAME = () => { 
    return (
       <div><h1>COMPONENT_NAME</h1></div> 
    );
}; 

export default COMPONENT_NAME;
Enter fullscreen mode Exit fullscreen mode

For the styling, create an empty component.css file.

In the template, we use COMPONENT_NAME as a placeholder that will be replaced with the actual component name during the generation process.

Step 2: Creating the Shell Script

Now, let's create the shell script that will generate React components based on the template.

Open a text editor and create a new file named generate-component.sh. Place the file in the root folder of your project or anywhere you want. For the example, we'll add the script in the root directory of an existing React project.

Copy and paste the following code into the file:

#!/bin/bash 

# Prompt the user to enter the path to the component template
read -p "Enter the template path: " template

# Prompt the user to enter the path where the component will be created
read -p "Enter the destination where you want to create the new component: " dest

# Prompt the user to enter the name of the component
read -p "Enter the name of the component: " component_name
Enter fullscreen mode Exit fullscreen mode

The first step is to use prompt to get the necessary information about the component. The first line reads our input for the path where the template component is located. The second line, reads our input for the path where we want to create the new component, and the third line reads out input for the name of the new component. This can be case insensitive since later in the script we'll capitalize the component name.

Next we'll check whether the template folder or destination folder given by us exist. If the destination folder i.e the new component location folder doesn't exist, it is created. Add the following code in the script:

#!/bin/bash

# Check if the template folder exists
if [! -d "$template"]; then
echo "Template folder '$template' does not exist."
exit 1
fi

# Check if the destination folder exists, if not, create it
if [! -d "$dest/$component_name"]; then
mkdir -p "$dest/$component_name"
fi 
Enter fullscreen mode Exit fullscreen mode

Next, what we want to do is copy all contents from the template folder to the newly created component folder. Add the following commands to the script:

#!/bin/bash 

# Copy all contents from the template folder to the destination folder
cp -R "$template"/* "$dest/$component_name"
Enter fullscreen mode Exit fullscreen mode

You should see the new folder created with the same files as the template.

Next, we'll improve the script a bit and make all the renaming to customize the new component.

First, we'll capitalize the component name and replace the placeholder with our new component name, and then we'll rename the component.css file to our component_name.css. If you're using scss or other, you'll need to adapt the script to use that file extention.

#!/bin/bash 

# Capitalize the first letter of the component name
first_letter = $(echo "${component_name:0:1}" | tr '[:lower:]' '[:upper:]')
capitalized_name = "${first_letter}${component_name:1}"

# rename all occurencies of COMPONENT_NAME with the capitalized component
find "$dest/$component_name" - type f - exec sed - i '' - e "s/COMPONENT_NAME/$capitalized_name/g" { } +

# rename the css file from component.css to $component_name.css
mv "$dest/$component_name/component.css" "$dest/$component_name/$component_name.css"
Enter fullscreen mode Exit fullscreen mode

And finally, we'll print a success message that will tell us that the component is created successfully.

#!/bin/bash 

echo "Component '$capitalized_name' created successfully!" 
Enter fullscreen mode Exit fullscreen mode

Step 3: Running the Script

To run the script, open a terminal, navigate to the directory where the script file is located, and execute the following command:

sh ./generate-component.sh
Enter fullscreen mode Exit fullscreen mode

Note that you might need to change the permissions to run the script. To make the file executable you can run

chmod +x generate-component.sh
Enter fullscreen mode Exit fullscreen mode

Once you run the script, it will prompt you to enter the template path, the location where you want the component to be created and the component name. If you want to make the generation quicker without option to enter the path names, you can adapt the script to use pre-defined locations for the template and the components folder.

After entering the information, the script will generate a new component file based on the template, replacing the placeholder with the provided component name.

Step 4: Generating components using npm in a React project

This step covers incorporating the script in an existing React project and running it using npm.

First, place the script we created in the previous steps in the React project where you want to automate component generation. You can add it either to the root directory, in a new scripts folder etc.

Next, open the package.json file and scroll down to the "scripts" property.

Add the following code in the scripts part:

"generate-component": "sh ./generate-component.sh"
Enter fullscreen mode Exit fullscreen mode

You can also name the script however you like. Save the file and you should be able to run it by running

npm run generate-component
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this blog post, we've explored how to create a shell script to automate the generation of React components using a predefined template. With this script, you can save time and effort by quickly generating components with a consistent structure.

Feel free to enhance the script further based on your specific requirements, such as generating additional files (e.g., stylesheets) or adding more complex logic.

Top comments (3)

Collapse
 
adrianolupossa profile image
Adriano Lupossa

There's some errors on the script that prevent to run

Collapse
 
mitevskasar profile image
Sara

Would you mind sharing the errors? So that I can help and update the script

Collapse
 
adrianolupossa profile image
Adriano Lupossa

It has some minor issues, but the idea is good. Some of them are:

  1. The "read" command shouldn't have a space between the "-" and the "p"

  2. In the if statements it should have space around its operators "[ ! -d "$template" ]"