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 🙏

© 2025 – Pkg Stats / Ryan Hefner

i18n-types-generator

v1.0.5

Published

A CLI tool for generating TypeScript types from i18next translation files

Downloads

317

Readme

i18n Types Generator

A CLI tool for generating TypeScript types from i18next translation files. This tool automatically creates type-safe interfaces for your internationalization files, ensuring type safety when using i18next with TypeScript.

Features

  • 🔧 Automatic Type Generation: Creates TypeScript interfaces from your translation JSON files
  • 🌍 i18next Integration: Full compatibility with i18next and react-i18next
  • 📁 Flexible Structure: Supports both simple and complex directory structures
  • 🎯 Type Safety: Ensures compile-time safety for translation keys
  • 🚀 CLI Tool: Easy to integrate into your build process
  • 📦 Zero Dependencies: Minimal runtime dependencies

Installation

# Install globally
npm install -g i18n-types-generator

# Or install as dev dependency
npm install --save-dev i18n-types-generator

Quick Start (No Installation Required)

If you don't want to install the package globally, you can use npx to run it directly:

# Create a configuration file
npx i18n-types-generator init

# Generate types
npx i18n-types-generator

# Generate with custom options
npx i18n-types-generator --locales ./src/locales --output ./types

Usage

Configuration File

Create a configuration file to customize the behavior:

# If installed globally
i18n-types-gen init

# If using npx (recommended for beginners)
npx i18n-types-generator init

# Create config file at custom location
npx i18n-types-generator init --output my-config.js

The tool automatically detects your project type and creates the appropriate config file format:

For CommonJS projects (creates i18n-types.config.js):

module.exports = {
    // Path to your locales directory
    localesPath: "./src/locales",

    // Output directory for generated types
    outputDir: "./types",

    // Default namespace for i18next
    defaultNamespace: "Common",

    // Base locale to use for type generation
    baseLocale: "ru",
};

For ES Module projects (creates i18n-types.config.mjs):

export default {
    // Path to your locales directory
    localesPath: "./src/locales",

    // Output directory for generated types
    outputDir: "./types",

    // Default namespace for i18next
    defaultNamespace: "Common",

    // Base locale to use for type generation
    baseLocale: "ru",
};

Manual format selection:

# Force CommonJS format
npx i18n-types-generator init --output i18n-types.config.cjs

# Force ES Module format
npx i18n-types-generator init --output i18n-types.config.mjs

# Auto-detect based on project type
npx i18n-types-generator init

CLI Usage

With npx (no installation required):

# Use config file (auto-detected)
npx i18n-types-generator

# Use specific config file
npx i18n-types-generator --config ./my-config.js

# Override config with CLI options
npx i18n-types-generator --locales ./src/locales --output ./types

# With verbose output
npx i18n-types-generator --verbose

If installed globally:

# Use config file (auto-detected)
i18n-types-gen

# Use specific config file
i18n-types-gen --config ./my-config.js

# Override config with CLI options
i18n-types-gen --locales ./src/locales --output ./types

# With verbose output
i18n-types-gen --verbose

CLI Options

  • -c, --config <path> - Path to config file
  • -l, --locales <path> - Path to locales directory (overrides config)
  • -o, --output <path> - Output directory for generated types (overrides config)
  • -d, --default-namespace <name> - Default namespace (overrides config)
  • -b, --base-locale <locale> - Base locale to use for type generation (overrides config)
  • --verbose - Enable verbose logging

CLI Commands

With npx:

  • npx i18n-types-generator - Generate types using config file or default options
  • npx i18n-types-generator init - Create a default configuration file

If installed globally:

  • i18n-types-gen - Generate types using config file or default options
  • i18n-types-gen init - Create a default configuration file

Programmatic Usage

import { I18nTypesGenerator } from "i18n-types-generator";

const generator = new I18nTypesGenerator({
    localesPath: "./src/locales",
    outputDir: "./types",
    defaultNamespace: "Common",
    baseLocale: "en",
});

generator.generate();

Directory Structure

The tool supports two directory structures:

Simple Structure

src/locales/
├── Common/
│   └── en.json
├── Auth/
│   └── en.json
└── Dashboard/
    └── en.json

Complex Structure (Meta namespace)

src/locales/
├── Common/
│   └── en.json
├── Auth/
│   └── en.json
└── Meta/
    ├── Users/
    │   └── en.json
    ├── Products/
    │   └── en.json
    └── Orders/
        └── en.json

Generated Files

The tool generates two files in your output directory:

i18n.interfaces.d.ts

Contains the namespace interfaces:

export interface CommonNamespace {
    welcome: string;
    "hello.world": string;
}

export interface AuthNamespace {
    login: string;
    logout: string;
}

i18n.d.ts

Contains the main type definitions and module declarations:

import { CommonNamespace, AuthNamespace } from "./i18n.interfaces";

declare module "i18next" {
    interface CustomTypeOptions {
        defaultNS: "Common";
        resources: {
            Common: CommonNamespace;
            Auth: AuthNamespace;
        };
    }
}

export type TranslationKey = `l:Common.${keyof CommonNamespace}` | `l:Auth.${keyof AuthNamespace}`;

Integration with TypeScript Projects

  1. Add the generated types to your TypeScript configuration:
{
    "compilerOptions": {
        "typeRoots": ["./types", "./node_modules/@types"]
    }
}
  1. Use with standard react-i18next (basic type safety):
import { useTranslation } from "react-i18next";

function MyComponent() {
    const { t } = useTranslation();

    // Basic type safety through i18next module augmentation
    // TypeScript knows about namespaces but not specific keys
    return <div>{t("welcome", { ns: "Common" })}</div>;
}
  1. Use the enhanced type-safe hooks (full type safety):
// Import the enhanced hooks from the package for full type safety
import { useTranslation, t } from "i18n-types-generator/react";
// Import the generated TranslationKey type
import type { TranslationKey } from "./types/i18n";

function MyComponent() {
    // Specify the type parameter to get full type safety
    const { t } = useTranslation<TranslationKey>();

    // Fully type-safe with autocomplete - no type assertions needed!
    return <div>{t("l:Common.welcome")}</div>;
}

// Or use the standalone t function (requires type parameter in function call)
const message = t("l:Auth.login"); // Works with module augmentation

Important Note:

  • Standard react-i18next: Gets basic type safety through i18next module augmentation (knows namespaces, not specific keys)
  • Enhanced hooks: Get full type safety by importing the generated TranslationKey type and using it as a type parameter
  • The generated types include module augmentation that automatically enhances the default behavior of the hooks
  • You can use either the type parameter approach or rely on the module augmentation for automatic typing

Package.json Scripts

Add to your package.json:

{
    "scripts": {
        "types:i18n": "npx i18n-types-generator",
        "i18n:watch": "nodemon --watch src/locales -e json --exec \"npm run types:i18n\"",
        "build": "npm run types:i18n && tsc"
    },
    "devDependencies": {
        "nodemon": "^3.0.0"
    }
}

Note: If you have the package installed globally, you can use "types:i18n": "i18n-types-gen" instead.

Development Workflow

For automatic type generation during development:

# Install nodemon for file watching
npm install --save-dev nodemon

# Run the watch script
npm run i18n:watch

This will automatically regenerate types whenever you modify your translation JSON files, providing a smooth development experience with always up-to-date TypeScript definitions.

Example Translation Files

Common/en.json

{
    "welcome": "Welcome",
    "hello": {
        "world": "Hello World"
    },
    "buttons": {
        "save": "Save",
        "cancel": "Cancel"
    }
}

Auth/en.json

{
    "login": "Login",
    "logout": "Logout",
    "register": "Register",
    "forgot": {
        "password": "Forgot Password"
    }
}

This will generate types like:

export interface CommonNamespace {
    welcome: string;
    "hello.world": string;
    "buttons.save": string;
    "buttons.cancel": string;
}

export interface AuthNamespace {
    login: string;
    logout: string;
    register: string;
    "forgot.password": string;
}

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT License - see the LICENSE file for details.

Support

If you encounter any issues or have questions, please file an issue on the GitHub repository.