i18next TypeScript Key Extractor

0.3.2 · active · verified Tue Apr 21

i18next-typescript-parser is a specialized utility library designed to accurately extract internationalization (i18n) keys from TypeScript codebases, tailored for use with the i18next framework. Unlike traditional parsers that might rely on less precise lexical analysis, this tool leverages a typed syntax tree (AST). This approach provides significantly enhanced reliability and precision in identifying translation keys within complex TypeScript structures, minimizing false positives and ensuring a more complete extraction compared to token-based methods. The current stable version is 0.3.2. As a 0.x.x series library, it is actively developed, and minor versions may introduce breaking changes. Its key differentiator is its robust, type-aware parsing mechanism, making it particularly valuable for maintaining accurate i18n key management in modern TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to import and use `extractKeys` to find i18next translation keys within a TypeScript file.

import { extractKeys } from 'i18next-typescript-parser';
import * as path from 'path';
import * as fs from 'fs';

// Imagine you have a directory with TypeScript files like this:
// project-root/src/components/MyComponent.ts
// project-root/src/utils/i18n.ts

// Create a dummy TypeScript file for demonstration
const dummyFilePath = path.join(__dirname, 'temp_i18n_test.ts');
fs.writeFileSync(dummyFilePath, `
  import { useTranslation } from 'react-i18next';
  
  function MyComponent() {
    const { t } = useTranslation('common');
    console.log(t('greeting'));
    console.log(t('welcome.message', { name: 'User' }));
    console.log(t('nested:key.path'));
    return <div>{t('button.label')}</div>;
  }
  
  const anotherKey = t('sidebar.item');
`);

// In a real scenario, you'd configure a tsconfig.json
// and pass it to extractKeys along with glob patterns for your source files.
// For this example, we'll try to extract keys directly.

console.log('Extracting i18next keys...');
const keys = extractKeys({
  // For a real project, configure 'project' to point to your tsconfig.json
  // For this example, we define a dummy project just to process the temp file
  project: [
    {
      name: 'temp_project',
      tsconfig: {
        compilerOptions: { target: 'esnext', module: 'commonjs', lib: ['dom', 'esnext'] },
        include: [dummyFilePath]
      },
      patterns: [dummyFilePath]
    }
  ]
});

if (keys.length === 0) {
  console.warn('No keys extracted. Ensure your tsconfig and patterns are correct.');
} else {
  console.log('Extracted Keys:');
  for (const { namespace, key } of keys) {
    console.log(`Namespace: ${namespace || '(default)'}, Key: ${key}`);
  }
}

// Clean up the dummy file
fs.unlinkSync(dummyFilePath);

view raw JSON →