Skip to content

Instantly share code, notes, and snippets.

@CobyBoy
Created March 26, 2025 13:13
Show Gist options
  • Save CobyBoy/f963fe3f90371ef51a0b23e4493778f2 to your computer and use it in GitHub Desktop.
Save CobyBoy/f963fe3f90371ef51a0b23e4493778f2 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
// Get the component name from the command-line arguments
const args = process.argv.slice(2);
const cssFlag = args.includes('--css') || args.includes('-css');
const componentName = args.map(word => word[0].toUpperCase() + word.slice(1)).join('');
console.log('nombre del componente', args.map(word => word[0].toUpperCase() + word.slice(1)).join(''))
if (!componentName) {
console.error('❌ Please provide a component name.');
console.log('Usage: npm run create-component -- <ComponentName>');
process.exit(1);
}
// Define paths
const componentDir = path.join('src', 'components', componentName);
// Check if the component folder already exists
if (fs.existsSync(componentDir)) {
console.error(`❌ A component with the name "${componentName}" already exists.`);
process.exit(1);
}
// Templates
const componentTemplate = `
import styles from './${componentName}.module.css';
export const ${componentName} = () => {
return <div className={styles.myClass}>Hello, ${componentName}!</div>;
};
`;
const cssTemplate = `
.myClass {
/* Add your styles here */
}
`;
const testTemplate = `
import { render, screen } from '@testing-library/react';
import ${componentName} from './${componentName}';
test('renders ${componentName} component', () => {
render(<${componentName} />);
expect(screen.getByText('Hello, ${componentName}!')).toBeInTheDocument();
});
`;
// Create the component directory and files
try {
fs.mkdirSync(componentDir, { recursive: true });
fs.writeFileSync(path.join(componentDir, `${componentName}.tsx`), componentTemplate.trim());
if (!cssFlag) {
fs.writeFileSync(path.join(componentDir, `${componentName}.module.css`), cssTemplate.trim());
}
fs.writeFileSync(path.join(componentDir, `${componentName}.test.tsx`), testTemplate.trim());
console.log(`✅ Component ${componentName} created successfully at ${componentDir}`);
} catch (error) {
console.error(`❌ Error creating component: ${error.message}`);
process.exit(1);
}
"scripts": {
"create": "node scripts/create-react-component.js"
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment