Generate modules with clean code for Typescript projects
npm install clegen---
- What is Clegen?
- Features
- Installation
- Quick Start
- Usage
- Interactive Mode
- CLI Flags Mode
- Available Options
- Project Structure
- Supported Frameworks
- Module Elements
- Examples
- Extending Clegen
- Adding a New Framework
- Adding a New Template
- Adding Custom Elements
- Contributing
- License
---
Clegen (Clean Generator) is a powerful command-line tool designed to scaffold clean architecture modules in TypeScript projects. It helps you maintain consistent code structure, enforces separation of concerns, and speeds up development by generating boilerplate code following best practices.
- ā
Consistent Architecture: Generates modules following Clean Architecture principles
- ā
Framework Agnostic: Supports Express, Hono, Next.js, and easily extensible
- ā
Concept-Based Organization: Files organized by concept (routes, services, domain, etc.)
- ā
Type-Safe: Full TypeScript support with proper imports
- ā
Extensible: Plugin architecture allows adding new frameworks and templates
- ā
React & React Native: Built-in support for React components and React Native styles
- ā
Time-Saving: Generate complete modules in seconds
---
- šÆ Concept-Based File Organization: Files grouped by their purpose (routes, services, domain, infrastructure, etc.)
- š Multiple Backend Frameworks: Express, Hono, Next.js
- āļø React & React Native Support: Components, hooks, and platform-specific styles
- šļø Clean Architecture Layers: Domain, Services, Infrastructure separation
- š¦ Modular Templates: Repository pattern, service layer, entities, types
- šØ Style Support: CSS and React Native StyleSheet
- š CLI or Interactive: Use flags for automation or interactive prompts for flexibility
- š§© Plugin Architecture: Easy to extend with new frameworks and templates
---
Use Clegen directly without installation:
``bash`
npx clegen@latest
`bash`
npm install -g clegen
`bash`
npm install clegen --save-dev
---
Generate a complete module in seconds:
`bashInteractive mode
npx clegen@latest
---
Usage
$3
Simply run
clegen and follow the prompts:`bash
npx clegen@latest
`The tool will ask you:
1. Module name (e.g., User, Product, Order)
2. Framework (Express, Hono, Next.js)
3. Elements to generate (routes, services, components, etc.)
4. Module path (where to create the module)
5. Implementation type (optional, e.g., MongoDB, PostgreSQL)
$3
Skip prompts by providing configuration via flags:
`bash
npx clegen@latest \
--name User \
--framework express \
--elements routes,service,types,repository \
--path ./src/modules/User \
--implementation MongoDB
`$3
| Flag | Shorthand | Description | Example |
|------|-----------|-------------|---------|
|
--name | -n | Module name (PascalCase) | User, Product |
| --framework | -f | Backend framework | express, hono, nextjs |
| --elements | -e | Comma-separated elements | routes,service,types |
| --path | -p | Module output path | ./src/modules/User |
| --implementation | -i | Implementation type | MongoDB, PostgreSQL |
| --help | -h | Show help message | - |---
Project Structure
Clegen organizes files by concept, not by layer. This makes related code easier to find:
`
User/
āāā routes/ # API endpoint handlers
ā āāā UserRouter.ts
āāā services/ # Business logic layer
ā āāā UserService.ts
āāā components/ # React components and hooks
ā āāā User.tsx
ā āāā useUser.tsx
āāā styles/ # CSS and React Native styles
ā āāā User.css
ā āāā User.styles.ts
āāā domain/ # Entities, types, repositories
ā āāā User.ts
ā āāā UserTypes.ts
ā āāā UserRepository.ts
āāā infrastructure/ # Schemas, implementations
ā āāā UserSchemas.ts
ā āāā MongoDBUserRepository.ts
āāā utils/ # Utility functions
āāā UserUtils.ts
`$3
| Group | Purpose | Contains |
|-------|---------|----------|
| routes/ | HTTP handlers | API route definitions |
| services/ | Business logic | Service classes with domain logic |
| components/ | UI layer | React components and custom hooks |
| styles/ | Presentation | CSS and React Native StyleSheet |
| domain/ | Core domain | Entities, types, repository interfaces |
| infrastructure/ | External concerns | DB schemas, repository implementations |
| utils/ | Helpers | Utility functions |
---
Supported Frameworks
$3
| Framework | Template | Example |
|-----------|----------|---------|
| Express | REST API routes |
Router() with service integration |
| Hono | Lightweight routes | Hono() app with handlers |
| Next.js | API routes | Next.js API route handlers |$3
| Framework | Template | Example |
|-----------|----------|---------|
| React | Components, Hooks | Functional components with TypeScript |
| React Native | Native styles |
StyleSheet.create() |---
Module Elements
Clegen can generate the following elements:
| Element | Description | Group | File Example |
|---------|-------------|-------|--------------|
|
routes | API endpoint handlers | routes | UserRouter.ts |
| service | Business logic layer | services | UserService.ts |
| component | React component | components | User.tsx |
| hook | React custom hook | components | useUser.tsx |
| styles | CSS styles | styles | User.css |
| styles-native | React Native styles | styles | User.styles.ts |
| types | TypeScript types/interfaces | domain | UserTypes.ts |
| entity | Domain entity | domain | User.ts |
| repository | Repository interface | domain | UserRepository.ts |
| schema | Validation schemas (Zod) | infrastructure | UserSchemas.ts |
| implementation | Repository implementation | infrastructure | MongoDBUserRepository.ts |
| utils | Utility functions | utils | UserUtils.ts |---
Examples
$3
`bash
npx clegen@latest \
--name Product \
--framework express \
--elements routes,service,types,repository,implementation \
--implementation MongoDB
`Generated files:
`
Product/
āāā routes/UserRouter.ts # Express router
āāā services/ProductService.ts # Business logic
āāā domain/ProductTypes.ts # TypeScript types
āāā domain/ProductRepository.ts # Repository interface
āāā infrastructure/MongoDBProductRepository.ts # MongoDB implementation
`$3
`bash
npx clegen@latest \
--name UserProfile \
--elements component,hook,styles,types
`Generated files:
`
UserProfile/
āāā components/UserProfile.tsx # React component
āāā components/useUserProfile.tsx # Custom hook
āāā styles/UserProfile.css # CSS styles
āāā domain/UserProfileTypes.ts # TypeScript types
`$3
`bash
npx clegen@latest \
--name Profile \
--elements component,hook,styles-native,types
`Generated files:
`
Profile/
āāā components/Profile.tsx # React component
āāā components/useProfile.tsx # Custom hook
āāā styles/Profile.styles.ts # React Native StyleSheet
āāā domain/ProfileTypes.ts # TypeScript types
`$3
`bash
npx clegen@latest \
--name Order \
--framework hono \
--elements routes,service,component,hook,styles,types,entity,repository,schema,implementation \
--implementation PostgreSQL
`Generated files:
`
Order/
āāā routes/OrderRoutes.ts # Hono routes
āāā services/OrderService.ts # Business logic
āāā components/Order.tsx # React component
āāā components/useOrder.tsx # Custom hook
āāā styles/Order.css # CSS styles
āāā domain/Order.ts # Entity
āāā domain/OrderTypes.ts # Types
āāā domain/OrderRepository.ts # Repository interface
āāā infrastructure/OrderSchemas.ts # Zod schemas
āāā infrastructure/PostgreSQLOrderRepository.ts # PostgreSQL implementation
`---
Extending Clegen
Clegen is designed to be easily extensible. You can add new frameworks, templates, and elements.
$3
1. Create a framework plugin in
src/plugins/frameworks/:`typescript
// src/plugins/frameworks/FastifyPlugin.ts
import { FrameworkPlugin } from '../../core/types/FrameworkPlugin';
import { GenerationContext, FileOutput } from '../../core/types/GenerationContext';
import { TemplateReader } from '../../core/base/TemplateReader';export class FastifyPlugin extends TemplateReader implements FrameworkPlugin {
readonly id = 'fastify' as const;
readonly name = 'Fastify';
async generate(context: GenerationContext): Promise {
const content = await this.readTemplate('routes/fastify.md', context);
return {
relativePath:
${context.entityName}Routes.ts,
content,
};
}
}
`2. Create the template in
src/fixtures/templates/routes/:`markdown
import { FastifyInstance } from 'fastify';
import { {{ entity }}Service } from './{{ Entity }}Service';export async function {{ entity }}Routes(fastify: FastifyInstance) {
fastify.get('/{{ entity }}', async (request, reply) => {
const items = await {{ entity }}Service.getAll();
return items;
});
fastify.get('/{{ entity }}/:id', async (request, reply) => {
const { id } = request.params as { id: string };
const item = await {{ entity }}Service.getById(id);
return item;
});
fastify.post('/{{ entity }}', async (request, reply) => {
const item = await {{ entity }}Service.create(request.body);
return item;
});
}
`3. Register the plugin in
src/plugins/plugins.config.ts:`typescript
import { FastifyPlugin } from './frameworks/FastifyPlugin';export const FRAMEWORK_PLUGINS = {
express: new ExpressPlugin(),
hono: new HonoPlugin(),
nextjs: new NextJsPlugin(),
fastify: new FastifyPlugin(), // Add your plugin
};
`$3
1. Create a template provider in
src/plugins/templates/:`typescript
// src/plugins/templates/GraphQLResolverTemplate.ts
import { TemplateProvider } from '../../core/types/TemplateProvider';
import { GenerationContext, FileOutput } from '../../core/types/GenerationContext';
import { TemplateReader } from '../../core/base/TemplateReader';export class GraphQLResolverTemplate extends TemplateReader implements TemplateProvider {
readonly id = 'resolver' as const;
readonly name = 'GraphQL Resolver';
readonly category = 'api' as const;
async generate(context: GenerationContext): Promise {
const content = await this.readTemplate('graphql/resolver.md', context);
return {
relativePath:
${context.entityName}Resolver.ts,
content,
};
}
}
`2. Create the template file:
`markdown
import { {{ entity }}Service } from '../services/{{ Entity }}Service';export const {{ entity }}Resolvers = {
Query: {
{{ entity }}: async (_: any, { id }: { id: string }) => {
return await {{ entity }}Service.getById(id);
},
{{ entity }}s: async () => {
return await {{ entity }}Service.getAll();
},
},
Mutation: {
create{{ Entity }}: async (_: any, { input }: { input: any }) => {
return await {{ entity }}Service.create(input);
},
},
};
`3. Register in plugins.config.ts:
`typescript
import { GraphQLResolverTemplate } from './templates/GraphQLResolverTemplate';export const TEMPLATE_PROVIDERS = {
// ... existing templates
resolver: new GraphQLResolverTemplate(),
};
`$3
1. Add to
ModuleElement type in src/core/types/GenerationContext.ts:`typescript
export type ModuleElement =
| "routes"
| "service"
// ... existing elements
| "resolver" // Add your new element
| "graphql-schema";
`2. Map to concept group in
src/core/types/ConceptMapping.ts:`typescript
export const ELEMENT_TO_GROUP: Record = {
// ... existing mappings
resolver: 'routes',
'graphql-schema': 'infrastructure',
};
`3. Add to multiselect in
src/Generators/ModularGenerator.ts:`typescript
const { elements } = await prompt<{ elements: ModuleElement[] }>({
type: "multiselect",
name: "elements",
choices: [
// ... existing choices
{ role: "separator", message: "āā GraphQL āā" },
{ name: "resolver", message: "GraphQL Resolver - Query/Mutation handlers" },
{ name: "graphql-schema", message: "GraphQL Schema - Type definitions" },
],
});
`---
Contributing
Contributions are welcome! Here's how you can help:
$3
1. Fork and clone the repository:
`bash
git clone https://github.com/mvrcoag/clegen.git
cd clegen
`2. Install dependencies:
`bash
npm install
`3. Build the project:
`bash
npm run prepare
`4. Link for local testing:
`bash
npm link
`5. Test your changes:
`bash
clegen --name Test --framework express --elements routes,service
`$3
`
clegen/
āāā src/
ā āāā core/ # Core types and base classes
ā ā āāā types/ # TypeScript types and interfaces
ā ā āāā base/ # Base classes (TemplateReader, CliParser)
ā āāā plugins/ # Framework and template plugins
ā ā āāā frameworks/ # Framework plugins (Express, Hono, etc.)
ā ā āāā templates/ # Template providers
ā ā āāā plugins.config.ts # Plugin registry
ā āāā Generators/ # Generator classes
ā ā āāā ModularGenerator.ts # Main generator
ā āāā fixtures/ # Template files
ā ā āāā templates/ # Markdown templates
ā āāā index.ts # CLI entry point
āāā dist/ # Compiled output
āāā scripts/ # Build scripts
`$3
- TypeScript: Use strict typing, avoid
any
- Templates: Use Markdown files with {{ placeholders }}
- Imports: Ensure cross-group imports use correct relative paths
- Tests: Add tests for new features (when test suite is available)
- Documentation: Update README for new features$3
1. Create a feature branch:
git checkout -b feature/my-feature
2. Make your changes
3. Build and test: npm run prepare && clegen --name Test ...
4. Commit: git commit -m "feat: add my feature"
5. Push: git push origin feature/my-feature`---
This project is licensed under the MIT License.
---