UNPKG

myex-cli

Version:

Opinionated Express.js framework with CLI tools

59 lines (48 loc) 1.92 kB
import path from 'path'; import fs from 'fs-extra'; import chalk from 'chalk'; import ora from 'ora'; import { fileURLToPath } from 'url'; import ejs from 'ejs'; import { camelCase, pascalCase } from '../utils/string-utils.js'; // Convert ES Module path const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const templatesDir = path.resolve(__dirname, '../templates/component'); /** * Generate a new component (can be any custom module) * @param {string} name - Component name */ export async function generateComponent(name) { const spinner = ora(`Generating component: ${chalk.blue(name)}`).start(); try { // Ensure proper casing const componentName = pascalCase(name); const componentNameCamel = camelCase(name); const componentFileName = `${componentNameCamel}.js`; // Ask where to place the component spinner.info(chalk.yellow('You can place the component in any directory.')); // Default to src/utils const destDir = path.join(process.cwd(), 'src', 'utils'); const destPath = path.join(destDir, componentFileName); // Check if component already exists if (fs.existsSync(destPath)) { spinner.warn(chalk.yellow(`Component ${componentFileName} already exists at ${destDir}. Skipping.`)); return; } // Load template const templateFile = path.join(templatesDir, 'component.template.ejs'); const template = await fs.readFile(templateFile, 'utf8'); // Render template const content = ejs.render(template, { componentName, componentNameCamel }); // Create component file await fs.ensureDir(destDir); await fs.writeFile(destPath, content, 'utf8'); spinner.succeed(chalk.green(`Component generated: ${destPath}`)); } catch (error) { spinner.fail(chalk.red(`Failed to generate component: ${error.message}`)); } }