i18next TypeScript Key Extractor
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
-
Error: Cannot find module 'typescript'
cause The `typescript` package, a peer dependency, is not installed in the project.fixInstall TypeScript: `npm install --save-dev typescript` or `yarn add --dev typescript`. -
SyntaxError: Cannot use import statement outside a module
cause Attempting to use the ES module `import` syntax in a CommonJS environment without proper transpilation or configuration.fixEnsure your Node.js environment supports ESM (Node.js 12+ with `"type": "module"` in `package.json` or by using a bundler like Webpack/Rollup if running in browser/transpiled environment). The library is primarily designed for ESM usage. -
TypeError: Cannot read properties of undefined (reading 'getSourceFile')
cause This error often indicates that the TypeScript compiler's program object was not correctly initialized, possibly due to an invalid `tsconfig.json` path or misconfigured `project` options when calling `extractKeys`.fixDouble-check the `project` configuration passed to `extractKeys`. Ensure the `tsconfig` path is correct and accessible, and that `include`/`files` arrays within your `tsconfig` correctly point to the files you want to parse.
Warnings
- breaking As a 0.x.x versioned package, `i18next-typescript-parser` does not adhere to semantic versioning strictly, meaning minor version bumps (e.g., 0.2.x to 0.3.x) may introduce breaking changes in API surface or behavior. Developers should review release notes carefully before upgrading.
- gotcha The parser relies on `typescript` as a peer dependency. Mismatches between the `typescript` version installed in your project and the version expected by `i18next-typescript-parser` can lead to parsing errors or unexpected behavior. This is especially true with major TypeScript releases.
- gotcha The precision of key extraction is highly dependent on how your `tsconfig.json` is configured and the `patterns` provided to `extractKeys`. Incorrect `include`, `exclude`, or `files` settings in `tsconfig` can result in keys not being found or unexpected files being parsed.
Install
-
npm install i18next-typescript-parser -
yarn add i18next-typescript-parser -
pnpm add i18next-typescript-parser
Imports
- extractKeys
const { extractKeys } = require('i18next-typescript-parser');import { extractKeys } from 'i18next-typescript-parser';
Quickstart
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);