Architecture
Templates

Templates

The template system handles code generation and content creation for React applications. It provides reusable patterns, framework-specific variations, and parameterized content based on user choices.

๐ŸŽจ Template Architecture


๐Ÿ“ Template Structure

src/templates/
โ”œโ”€โ”€ engines/                    # Core template infrastructure
โ”‚   โ”œโ”€โ”€ template-engine.js      # Main template rendering engine
โ”‚   โ”œโ”€โ”€ content-builder.js      # Content building utilities
โ”‚   โ””โ”€โ”€ template-utils.js       # Template helper functions
โ”œโ”€โ”€ frameworks/                 # Framework-specific templates
โ”‚   โ”œโ”€โ”€ vite/                   # Vite-specific templates
โ”‚   โ”œโ”€โ”€ nextjs/                 # Next.js-specific templates
โ”‚   โ””โ”€โ”€ index.js                # Framework template selector
โ””โ”€โ”€ features/                   # Feature-specific templates
    โ”œโ”€โ”€ redux/                  # Redux boilerplate templates
    โ”œโ”€โ”€ zustand/                # Zustand store templates
    โ”œโ”€โ”€ styling/                # Styling-specific templates
    โ””โ”€โ”€ testing/                # Testing templates

โš™๏ธ Template Engine

The core template engine handles content generation and rendering.

Template Rendering Process

Template Selection

Choose appropriate templates based on user choices:

const templateSelector = new TemplateSelector();
const templates = templateSelector.select({
  framework: "vite",
  typescript: true,
  styling: "tailwind",
  state: "redux",
});

Content Generation

Generate content using selected templates:

const contentBuilder = new ContentBuilder();
const generatedContent = await contentBuilder.build(templates, userChoices);

File Writing

Write generated content to the project:

for (const [filePath, content] of Object.entries(generatedContent)) {
  await writeFile(path.join(projectPath, filePath), content);
}

Template Engine Features

Dynamic Content Based on User Choices:

// Template with parameters
const appTemplate = `
import React from 'react'
${typescript ? "import type { FC } from 'react'" : ''}
${styling === 'tailwind' ? "import './index.css'" : ''}
${state === 'redux' ? "import { Provider } from 'react-redux'" : ''}
${state === 'redux' ? "import { store } from './store/store'" : ''}
 
${typescript ? 'const App: FC = () => {' : 'function App() {'}
  return (
    ${state === 'redux' ? '<Provider store={store}>' : ''}
    <div className="${styling === 'tailwind' ? 'min-h-screen bg-gray-100' : 'app'}">
      <h1>Welcome to React Kickstart!</h1>
    </div>
    ${state === 'redux' ? '</Provider>' : ''}
  )
}
 
export default App
`

๐Ÿ—๏ธ Framework Templates

Framework-specific templates handle the unique requirements of each React framework.

Vite Templates

// Generated App.tsx for Vite
import React from 'react'
{{#if routing}}
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import Home from './pages/Home'
import About from './pages/About'
{{/if}}
{{#if state === 'redux'}}
import { Provider } from 'react-redux'
import { store } from './store/store'
{{/if}}
{{#if styling === 'tailwind'}}
import './index.css'
{{/if}}
 
function App() {
  return (
    {{#if state === 'redux'}}<Provider store={store}>{{/if}}
    {{#if routing}}
    <BrowserRouter>
      <div className="{{#if styling === 'tailwind'}}min-h-screen bg-gray-100{{/if}}">
        <nav className="{{#if styling === 'tailwind'}}bg-white shadow-sm p-4{{/if}}">
          <Link to="/">Home</Link>
          <Link to="/about">About</Link>
        </nav>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </div>
    </BrowserRouter>
    {{else}}
    <div className="{{#if styling === 'tailwind'}}min-h-screen bg-gray-100 flex items-center justify-center{{/if}}">
      <div className="{{#if styling === 'tailwind'}}text-center{{/if}}">
        <h1 className="{{#if styling === 'tailwind'}}text-4xl font-bold text-gray-900 mb-4{{/if}}">
          Welcome to React Kickstart!
        </h1>
        <p className="{{#if styling === 'tailwind'}}text-lg text-gray-600{{/if}}">
          Your Vite + React app is ready to go.
        </p>
        {{#if state}}
        <Counter />
        {{/if}}
      </div>
    </div>
    {{/if}}
    {{#if state === 'redux'}}</Provider>{{/if}}
  )
}
 
export default App

Next.js Templates

// Generated app/layout.tsx (App Router)
{{#if styling === 'tailwind'}}
import './globals.css'
{{/if}}
{{#if typescript}}
import type { Metadata } from 'next'
{{/if}}
{{#if state === 'redux'}}
import { Providers } from './providers'
{{/if}}
 
{{#if typescript}}
export const metadata: Metadata = {
  title: '{{projectName}}',
  description: 'Generated by React Kickstart',
}
{{/if}}
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        {{#if state === 'redux'}}
        <Providers>
          {children}
        </Providers>
        {{else}}
        {children}
        {{/if}}
      </body>
    </html>
  )
}

๐ŸŽฏ Feature Templates

Feature-specific templates provide boilerplate code for different capabilities.

State Management Templates

// Generated Redux store template
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './counterSlice'
{{#each additionalSlices}}
import {{name}}Reducer from './{{name}}Slice'
{{/each}}
 
export const store = configureStore({
  reducer: {
    counter: counterReducer,
    {{#each additionalSlices}}
    {{name}}: {{name}}Reducer,
    {{/each}}
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: ['persist/PERSIST'],
      },
    }),
})
 
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

๐Ÿ”ง Template Customization

Adding Custom Templates

Create Template File

// src/templates/features/your-feature/component.template.js
export const componentTemplate = `
import React from 'react'
{{#if typescript}}
interface {{componentName}}Props {
  {{#each props}}
  {{name}}: {{type}}
  {{/each}}
}
{{/if}}
 
{{#if typescript}}
const {{componentName}}: React.FC<{{componentName}}Props> = ({{#if props}}{
  {{#each props}}{{name}}{{#unless @last}}, {{/unless}}{{/each}}
}{{/if}}) => {
{{else}}
function {{componentName}}({{#if props}}{
  {{#each props}}{{name}}{{#unless @last}}, {{/unless}}{{/each}}
}{{/if}}) {
{{/if}}
  return (
    <div>
      {{content}}
    </div>
  )
}
 
export default {{componentName}}
`;

Register Template

// src/templates/features/your-feature/index.js
import { componentTemplate } from "./component.template.js";
 
export class YourFeatureTemplates {
  getTemplates() {
    return {
      component: componentTemplate,
      // ... other templates
    };
  }
 
  generateComponent(name, props, content) {
    return this.render(componentTemplate, {
      componentName: name,
      props: props,
      content: content,
    });
  }
}

Use in Generator

// In your generator
const templates = new YourFeatureTemplates();
const componentCode = templates.generateComponent(
  "MyComponent",
  [
    { name: "title", type: "string" },
    { name: "onClick", type: "() => void" },
  ],
  "<h1>{title}</h1>"
);
 
await writeFile(
  path.join(projectPath, "src/components/MyComponent.tsx"),
  componentCode
);

๐Ÿงช Template Testing

Template Validation

Quality Assurance: All templates are validated through the QA automation system to ensure generated code compiles and runs correctly.

// Template testing example
describe("Component Templates", () => {
  it("should generate valid TypeScript component", () => {
    const template = new ComponentTemplate();
    const code = template.generate({
      componentName: "TestComponent",
      typescript: true,
      props: [{ name: "title", type: "string" }],
    });
 
    // Validate TypeScript compilation
    expect(() => typescript.transpile(code)).not.toThrow();
 
    // Validate React component structure
    expect(code).toContain("React.FC");
    expect(code).toContain("export default TestComponent");
  });
});

Integration Testing

// Test template integration with generators
describe("Template Integration", () => {
  it("should generate complete project with templates", async () => {
    const generator = new ViteGenerator();
    const projectPath = "/tmp/test-project";
 
    await generator.generate(projectPath, "test-project", {
      framework: "vite",
      typescript: true,
      state: "redux",
    });
 
    // Verify all template-generated files exist and are valid
    expect(fs.existsSync(path.join(projectPath, "src/App.tsx"))).toBe(true);
    expect(fs.existsSync(path.join(projectPath, "src/store/store.ts"))).toBe(
      true
    );
 
    // Verify generated code compiles
    const buildResult = await exec("npm run build", { cwd: projectPath });
    expect(buildResult.exitCode).toBe(0);
  });
});

๐Ÿ“š Next Steps

Explore Related Systems:

Extend React Kickstart:

Flexible Generation: The template system's flexibility allows for consistent code generation while supporting extensive customization based on user preferences.