mustache-ts-generator
v1.0.4
Published
Generate TypeScript interfaces from Mustache templates automatically
Maintainers
Readme
mustache-ts-generator
Generate TypeScript interfaces from Mustache templates automatically. Perfect for maintaining type safety in template-based applications.
Features
- 🚀 Automatic Interface Generation - Scan your
.mustachefiles and generate TypeScript interfaces - 👁️ Watch Mode - Automatically regenerate when templates change
- 📁 Flexible Output - Generate separate files or a single combined file
- 🎯 Smart Type Inference - Infers types from variable names (e.g.,
count→number,isActive→boolean) - 🔧 Fully Configurable - Custom type mappings, naming conventions, and more
- 🧩 Nested Section Support - Automatically generates nested interfaces for sections
- 🚫 Smart Excludes - Automatically ignores
node_modules,.git, and other system folders - 💻 Cross-Platform - Works on Windows, macOS, and Linux
- 📦 Zero Runtime - No runtime dependencies in your project
- 🏷️ Configurable Naming - Customizable suffixes for main interfaces (interfaceSuffix) and nested section interfaces (nestedInterfaceSuffix)
Installation
npm install --save-dev mustache-ts-generatorQuick Start
- Create your Mustache templates
<!-- templates/user.mustache -->
<h1>{{name}}</h1>
<p>Age: {{age}}</p>
<p>Active: {{isActive}}</p>
{{#users}}
<div>{{name}} - {{role}}</div>
{{/users}}- Generate TypeScript interfaces
npx mustache-ts-generator generate -i ./templates -o ./src/types- Use the generated interfaces
// src/types/user.types.ts (auto-generated from user.mustache)
export interface UserProps {
name: string;
age: string;
isActive: boolean;
users: UsersItem[]; // nested interface for {{#users}} section
}
// Nested interface (automatically generated)
export interface UsersItem {
name: string;
role: string;
}CLI Usage Generate command
# Basic usage (generates next to templates)
npx mustache-ts-generator generate -i ./templates
# Specify output directory
npx mustache-ts-generator generate -i ./templates -o ./src/types
# Generate single file with all interfaces
npx mustache-ts-generator generate -i ./templates --single-file -o ./src/types
# With custom config file
npx mustache-ts-generator generate -i ./templates -c ./config.json
# Generate interfaces next to templates (no output directory)
npx mustache-ts-generator generate -i ./templates
# Verbose output for debugging
npx mustache-ts-generator generate -i ./templates --verboseWatch mode
# Watch for changes and regenerate automatically
npx mustache-ts-generator watch -i ./templates -o ./src/types
# Custom debounce time (default 300ms)
npx mustache-ts-generator watch -i ./templates -o ./src/types --debounce 500Initialize configuration
npx mustache-ts-generator generate --initConfiguration Create .mustache-types.json in your project root:
{
"interfaceSuffix": "props",
"nestedInterfaceSuffix": "Item",
"camelCase": false,
"skipEmptyInterfaces": false,
"singleFile": false,
"singleFileName": "mustache-types.ts",
"outputDirectory": "./src/@types/mustache",
"typeMapping": {
"default": "string",
"*Date": "string", // override all dates to string
"age": "number", // exact match
"user.*.id": "string" // nested pattern
},
"excludeDirs": ["temp", "cache", "custom-folder"]
}Or in package.json:
{
"name": "my-project",
"mustacheTypes": {
"outputDirectory": "./src/types",
"interfaceSuffix": "Template"
}
}Configuration Options
Options
| Name | Type | Default | Description |
|:-----------------------------------------------------:| :-------------------: |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:--------------------------------------------------|
| interfaceSuffix | {string} | "props" | Suffix for generated interface files |
| nestedInterfaceSuffix | {string} | "Item" | Suffix for nested section interfaces (e.g., UsersItem for {{#users}}) |
| outputDirectory | {string} | undefined | Directory where interface files will be generated |
| camelCase | {boolean} | false | Convert field names to camelCase |
| skipEmptyInterfaces | {boolean} | false | Skip generating interface if no variables found |
| singleFile | {boolean} | false | Generate single file with all interfaces |
| singleFileName | {string} | mustache-types.ts | Name of single file when singleFile: true |
| typeMapping | {object} | {"default": "string"} | Custom type mapping for variables |
| excludeDirs | {string[]} | ["node_modules", ".git", "dist", "build", ".next", "coverage", ".nyc_output", "__pycache__", ".cache", "tmp", "temp", "out", "target", "bin", "obj", ".idea", ".vscode", ".vs", ".gradle", ".mvn", ".husky", ".github", "venv", "env", ".env"] | Directories to exclude from scanning |
❗The interfaceSuffix controls the suffix for the main template interface (e.g., UserProps). The nestedInterfaceSuffix controls the suffix for nested section interfaces (e.g., UsersItem for {{#users}}), preventing naming conflicts when a section has the same name as the template file.
Type Inference Rules
The generator intelligently infers TypeScript types based on variable names:
| Pattern | Inferred Type | Example |
|:---|:---|:----------------------------------------|
| *Count, *Total, *Index, *Num, *Amount | number | userCount, priceTotal, rowIndex |
| *Id | number | userId, productId |
| is*, has*, can*, should*, was* | boolean | isActive, hasPermission, canEdit |
| *Date, *Time, *At, *On | Date | createdAt, updatedDate, startTime |
| Plural names (*s, *ies) | any[] | users, categories |
| Nested paths (user.count) | Nested object | See example below |
| Default | string | name, title, description |
Nested Variables
Variables with dots are automatically converted to nested objects:
{{user.count}} {{user.name}} {{user.address.city}}Generated interface:
export interface UserProps {
count: number;
name: string;
address: {
city: string;
};
}Invalid Variable Names
If a variable name contains invalid characters or uses TypeScript keywords, the generator will:
Output an error message in the console
Encloses the variable name in brackets (if it contains invalid characters) and adds an explanatory comment regarding the invalid property to the generated interface.
Example:
{{user}name}} {{class}} {{123invalid}}Console output:
❌ Errors in template.mustache:
- Variable name "user}name" contains invalid characters
- Variable name "class" is a TypeScript keyword
- Variable name "123invalid" cannot start with a numberGenerated interface:
export interface TemplateProps {
'user}name': string; // Warning: Variable name "user}name" contains invalid characters.
class: string; // Warning: Variable name "class" is a TypeScript keyword.
'123invalid': string; // Warning: Variable name "123invalid" cannot start with a number.
}Integration Examples
Next.js
{
"scripts": {
"generate:types": "mustache-ts-generator generate -i ./src/templates -o ./src/@types/mustache",
"watch:types": "mustache-ts-generator watch -i ./src/templates -o ./src/@types/mustache",
"dev": "concurrently \"npm run watch:types\" \"next dev\"",
"build": "npm run generate:types && next build"
}
}With nodemon (alternative)
{
"scripts": {
"watch:types": "nodemon --watch 'src/templates/**/*.mustache' --exec 'mustache-ts-generator generate -i ./src/templates'",
"dev": "npm run watch:types & next dev"
}
}Advanced Usage
Programmatic API
import { MustacheTypeGenerator } from 'mustache-ts-generator';
const generator = new MustacheTypeGenerator({
outputDirectory: './src/types',
interfaceSuffix: 'Template',
nestedInterfaceSuffix: 'Nested',
camelCase: true,
typeMapping: {
default: 'string',
'user.id': 'number'
}
});
await generator.generateAll('./templates');Custom Type Mapping with Path Patterns
The typeMapping configuration allows you to override types for specific variables using:
1. Exact match by full path
{
"typeMapping": {
"user.id": "string",
"address.zipCode": "number",
"product.price": "number"
}
}- Wildcard patterns (using *)
{
"typeMapping": {
"*.id": "string", // all 'id' properties anywhere
"user.*.createdAt": "Date", // nested properties
"*Price": "number" // properties ending with 'Price'
}
}- Regular expressions (wrapped in /.../)
{
"typeMapping": {
"/.*\\.id$/": "string", // all properties ending with '.id'
"/.*\\.createdAt$/": "Date", // all properties ending with '.createdAt'
"/^user\\..*$/": "User" // all properties under 'user' object
}
}Priority order
Types are resolved in the following order:
Exact match in typeMapping
Regex patterns (wrapped in /.../)
Wildcard patterns (using *)
Built-in rules (numbers, booleans, dates, arrays)
Default (string)
Example Given this Mustache template:
<div>User: {{user.id}}, created: {{user.createdAt}} ({{user.tags}})</div>And this configuration:
{
"typeMapping": {
"/.*\\.id$/": "string",
"/.*\\.createdAt$/": "Date",
"/.*\\.tags$/": "string[]"
}
}Generated interface:
export interface UserProps {
id: string; // overridden by regex
createdAt: Date; // overridden by regex
tags: string[]; // overridden by regex
}Overriding built-in rules Built-in type inference can be overridden:
{
"typeMapping": {
"*Date": "string", // change all dates to string
"is*": "string", // change all booleans to string
"*.count": "string" // change numbers to string
}
}Excluding Custom Directories
# Via CLI
npx mustache-ts-generator generate -i ./ --exclude temp,cache,logs
# Via config
{
"excludeDirs": ["temp", "cache", "logs", "custom-folder"]
}Examples
Template with nested sections
❗Main interfaces use the interfaceSuffix (default: "props"), while nested section interfaces use the nestedInterfaceSuffix (default: "Item") to avoid naming conflicts.
<!-- company.mustache -->
<h1>{{name}}</h1>
{{#departments}}
<h2>{{name}}</h2>
{{#employees}}
<div>{{firstName}} {{lastName}} - {{role}}</div>
{{/employees}}
{{/departments}}Generated interfaces:
// company.props.ts
export interface EmployeeItem {
firstName: string;
lastName: string;
role: string;
}
export interface DepartmentsItem {
name: string;
employees: EmployeeItem[];
}
export interface CompanyProps {
name: string;
departments: DepartmentsItem[];
}Development
bash
Clone repository
git clone https://github.com/pbyh/mustache-ts-generator.git
Please read CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.
License
MIT © PByH
Changelog
See CHANGELOG.md for version history.
