TL;DR
Do you ever find yourself creating the same files over and over again and wish for a script to do the boring work for you without having to use a third-party library?
The story
I've been creating a lot of React components lately and wanted to find a way to automate file creation. Specifically, a script that could create a ComponentName folder containing the following files:
index.tsx
-
styles.tsx
After doing some research, I found that node's fs module is able to meet my needs. Specifically,
-
fs.mkdirSync(path)
synchronously creates a directory given a path (+ other options) -
fs.writeFileSync(filepath, content)
synchronously creates files in the given filepath and optionally fills them with content
Step 1: Defining the file templates
// src/scaffold.js
const templates = {
index: `// Comment to begin our index file`,
styles: `// Comment to begin our styles file`,
};
Step 2: Write functions to create the component folder and files
// src/scaffold.js
const fs = require("fs");
const args = process.argv.slice(2);
function createFolder(component) {
const directory = `./src/components/${component}`;
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
}
function writeFile(component, type) {
const filepath =`./src/components/${component}/${filename}.tsx`;
fs.writeFile(filepath, templates[type], (err) => {
if (err) throw err;
console.log("Created file: ", filepath);
return true;
});
}
function generate(component) {
createFolder(component);
const fileTypes = ["index", "styles"];
for (let type of fileTypes) {
writeFile(component, type)
}
}
generate(args[0]);
-
createFolder(component)
creates a folder namedcomponent
if it does not exist in the specified path -
writeFile(component, type)
creates files in the specified folder and fills them with content specified intemplates[type]
Step 3: Adding the script
Finally, add the following script to package.json
"scripts": {
"component": "node scaffold.js"
},
That's it! The magic command that is yarn component <ComponentName>
.
Let me know your thoughts in the comments below ๐
Top comments (0)