#!/usr/bin/env node const { program } = require('commander'); const fs = require('fs'); const path = require('path'); function createDirIfNotExist(srcDir) { if (!fs.existsSync(srcDir)) { fs.mkdirSync(srcDir, { recursive: true }); } } function ucfirst(str) { if (!str) return str; return str.charAt(0).toUpperCase() + str.slice(1); } createDirIfNotExist('./src'); program .version('1.0.0') .description('CLI for generating Ionic React pages and components'); program .command('generate ') .alias('g') .description('Generate a new page or component') .action((type, names) => { names.forEach(name => { if (type === 'p' || type === 'page') { generatePage(name); } else if (type === 'c' || type === 'component') { generateComponent(name); } else { console.log('Invalid type. Use "p" or "page" for page, and "c" or "component" for component.'); } }); }); program.parse(process.argv); function generatePage(name) { createDirIfNotExist('./src/pages'); const pageName = ucfirst(name); createDirIfNotExist(`./src/pages/${pageName}`); const templatePath = path.join(path.dirname(__dirname), 'templates', 'page-template.tsx'); const targetPath = path.join(process.cwd(), 'src', 'pages', pageName, `${name}.tsx`); generateFromTemplate(templatePath, targetPath, name); const stylePath = path.join(path.dirname(__dirname),'templates', 'page-template.css'); const targetStylePath = path.join('src', 'pages', `${ucfirst(name)}`, `${name}.css`); generateStyle(stylePath, targetStylePath, name); } function generateComponent(name) { createDirIfNotExist('./src/components'); const componentName = ucfirst(name); createDirIfNotExist(`./src/components/${componentName}`); const templatePath = path.join(path.dirname(__dirname), 'templates', 'component-template.tsx'); const targetPath = path.join(process.cwd(), 'src', 'components', componentName, `${name}.tsx`); generateFromTemplate(templatePath, targetPath, name); } function generateFromTemplate(templatePath, targetPath, name) { fs.readFile(templatePath, 'utf8', (err, data) => { if (err) { console.error(`Error reading template file: ${err}`); return; } const content = data.replace(/%NAME%/g, name); fs.writeFile(targetPath, content, 'utf8', (err) => { if (err) { console.error(`Error writing file: ${err}`); } else { console.log(`${targetPath} created successfully!`); } }); }); const stylePath = path.join(path.dirname(__dirname),'templates', 'component-template.css'); const targetStylePath = path.join('src', 'components', `${ucfirst(name)}`, `${name}.css`); generateStyle(stylePath, targetStylePath, name); } function generateStyle(templatePath, targetPath, name) { fs.readFile(templatePath, 'utf8', (err, data) => { if (err) { console.error(`Error reading template file: ${err}`); return; } const content = data.replace(/%NAME%/g, name); fs.writeFile(targetPath, content, 'utf8', (err) => { if (err) { console.error(`Error writing file: ${err}`); } else { console.log(`${targetPath} created successfully!`); } }); }); }