@tomdamri/rudolph
Version:
generate react component folder
75 lines (61 loc) • 2.68 kB
JavaScript
const fs = require('fs');
const path = require('path');
const { Command } = require('commander');
const program = new Command();
// Function to create a file with given content
const createFile = (filePath, content) => {
const dir = path.dirname(filePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(filePath, content, 'utf-8');
};
// Function to read and process template files
const processTemplate = (templatePath, componentName) => {
const template = fs.readFileSync(templatePath, 'utf-8');
return template.replace(/{{componentName}}/g, componentName);
};
// Main function to generate the component structure
const generateComponent = (componentName) => {
if (!componentName) {
console.error('Please provide a component name.');
process.exit(1);
}
const templatesDir = path.join(__dirname, 'templates');
const componentDir = path.join(process.cwd(), componentName);
const filesToGenerate = [
{ template: 'Component.tsx', target: `${componentName}.tsx` },
{ template: 'index.ts', target: 'index.ts' },
{ template: 'helpers.ts', target: 'helpers.ts' },
{ template: 'utils.ts', target: 'utils.ts' },
{ template: 'Types.ts', target: 'Types.ts' },
{ template: 'useComponent.ts', target: 'useComponent.ts' },
{ template: 'useStore.ts', target: 'useStore.ts' },
// { template: 'hooks/useSmallerHook.ts', target: 'hooks/useSmallerHook.ts' },
{ template: 'components/index.ts', target: 'components/index.ts' },
{ template: '_tests_/helpers.test.ts', target: '_tests_/helpers.test.ts' },
{ template: '_tests_/utils.test.ts', target: '_tests_/utils.test.ts' },
{ template: '_tests_/useComponent.test.ts', target: `_tests_/use${componentName}.test.ts` }
];
filesToGenerate.forEach(({ template, target }) => {
const templatePath = path.join(templatesDir, template);
const targetPath = path.join(componentDir, target);
const content = processTemplate(templatePath, componentName);
createFile(targetPath, content);
});
console.log(`Component ${componentName} created successfully!`);
};
// Setting up the commander program
program
.name('rudolph')
.description('CLI to generate React component folders')
.version('1.0.6');
program
.command('generate')
.description('Generate a new React component')
.argument('<componentName>', 'Name of the component to generate')
.action((componentName) => {
generateComponent(componentName);
});
program.parse(process.argv);