UNPKG

nextdevkit

Version:

A Comprehensive CLI Toolkit for Next.js Development

47 lines (46 loc) 2.24 kB
import chalk from 'chalk'; import fs from 'fs-extra'; import path from 'path'; import { __dirname } from '../utils/constants/package.constant.js'; import { handleError } from '../utils/handleMessages.js'; import isTypeScriptProject from '../utils/isTypescriptProject.js'; const generateComponents = async (type, name, destination) => { try { if (!type || !name) { console.log(chalk.red('❌ Please specify the type and name of the file to generate.')); console.log(chalk.yellow('Usage: npx nextdevkit@latest generate <type> <name> [--destination=<path>]')); console.log(chalk.green('Available Types: component')); return; } const validTypes = ['component']; if (!validTypes.includes(type.toLowerCase())) { console.log(chalk.red(`❌ Unknown type '${type}'. Available types are: ${validTypes .map((t) => `'${t}'`) .join(', ')}.`)); return; } const currentDirectory = process.cwd(); const isTs = isTypeScriptProject(currentDirectory); const templates = { component: path.join(__dirname, '..', 'templates', 'Component.tsx') }; const defaultDestination = path.join(currentDirectory, 'components', `${name}${isTs ? '.tsx' : '.jsx'}`); const destPath = destination ? path.resolve(currentDirectory, destination, `${name}${isTs ? '.tsx' : '.jsx'}`) : defaultDestination; const templatePath = templates[type.toLowerCase()]; if (!(await fs.pathExists(templatePath))) { console.log(chalk.red(`❌ Template file not found at ${templatePath}.`)); return; } const templateContent = await fs.readFile(templatePath, 'utf8'); const content = templateContent.replace(/__NAME__/g, name); await fs.ensureDir(path.dirname(destPath)); await fs.writeFile(destPath, content, 'utf8'); console.log(chalk.green(`✅ ${type.charAt(0).toUpperCase() + type.slice(1)} '${name}' created successfully at ${destPath}.`)); } catch (error) { handleError(`❌ Failed to generate the file: ${error}`); } }; export default generateComponents;