npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mustache-ts-generator

v1.0.4

Published

Generate TypeScript interfaces from Mustache templates automatically

Readme

mustache-ts-generator

npm version License: MIT TypeScript

Generate TypeScript interfaces from Mustache templates automatically. Perfect for maintaining type safety in template-based applications.

Features

  • 🚀 Automatic Interface Generation - Scan your .mustache files 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., countnumber, isActiveboolean)
  • 🔧 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-generator

Quick Start

  1. Create your Mustache templates
<!-- templates/user.mustache -->
<h1>{{name}}</h1>
<p>Age: {{age}}</p>
<p>Active: {{isActive}}</p>

{{#users}}
  <div>{{name}} - {{role}}</div>
{{/users}}
  1. Generate TypeScript interfaces
npx mustache-ts-generator generate -i ./templates -o ./src/types
  1. 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 --verbose

Watch 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 500

Initialize configuration

npx mustache-ts-generator generate --init

Configuration 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 number

Generated 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"
  }
}
  1. Wildcard patterns (using *)
{
  "typeMapping": {
    "*.id": "string",           // all 'id' properties anywhere
    "user.*.createdAt": "Date", // nested properties
    "*Price": "number"          // properties ending with 'Price'
  }
}
  1. 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:

  1. Exact match in typeMapping

  2. Regex patterns (wrapped in /.../)

  3. Wildcard patterns (using *)

  4. Built-in rules (numbers, booleans, dates, arrays)

  5. 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.