### Install and Run i18n-check CLI
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Install the i18n-check package as a development dependency. Use 'npx' to run the command if it's not globally installed or if you're not using npm scripts.
```bash
# Ensure package is installed
npm install --save-dev @lingual/i18n-check
# Use npx if not in npm scripts
npx i18n-check --locales translations/ -s en-US
# Or use full path
node_modules/.bin/i18n-check --locales translations/ -s en-US
```
--------------------------------
### FileInfo Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
An example demonstrating how to instantiate the FileInfo type with sample file path, name, and path segments. This is not typically used in the library API.
```typescript
const info: FileInfo = {
file: 'locales/de-DE/common.json',
name: 'common.json',
path: ['locales', 'de-DE']
};
```
--------------------------------
### Example Usage of StandardReporter
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
Example of how to structure a report object.
```typescript
const report: StandardReporter = {
file: 'locales/de-DE/common.json',
key: 'greeting',
msg: 'Missing element argument'
};
```
--------------------------------
### Options Example with default values
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
An example showing an empty Options object, which will result in all options using their default values. This is useful when no specific configuration is needed.
```typescript
const optionsDefault: Options = {};
```
--------------------------------
### Options Example with react-intl format
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
A minimal example of configuring validation options, specifying only the 'react-intl' format. Other options will use their default values.
```typescript
const optionsMinimal: Options = {
format: 'react-intl'
};
```
--------------------------------
### Install i18n-check with npm
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Install the i18n-check package as a development dependency using npm.
```bash
npm install --save-dev @lingual/i18n-check
```
--------------------------------
### Options Example with i18next format
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
An example of configuring validation options with the 'i18next' format, specifying checks for missing and invalid keys, and defining keys to ignore using wildcard patterns.
```typescript
const options: Options = {
format: 'i18next',
checks: ['missingKeys', 'invalidKeys'],
ignore: ['beta.*', 'internal.key'],
nextIntlTranslationFnTypeAlias: []
};
```
--------------------------------
### Show Version
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Displays the installed version of the i18n-check tool. Use either the long or short flag.
```bash
i18n-check --version
i18n-check -V
```
--------------------------------
### Install i18n-check with pnpm
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Install the i18n-check package as a development dependency using pnpm.
```bash
pnpm add --save-dev @lingual/i18n-check
```
--------------------------------
### Install i18n-check with Yarn
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Install the i18n-check package as a development dependency using Yarn.
```bash
yarn add --dev @lingual/i18n-check
```
--------------------------------
### Check Undefined Keys with next-intl Format
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-undefined-keys.md
Example for checking undefined keys with the next-intl format. It assumes a setup where translations are namespaced according to next-intl conventions.
```typescript
// Code:
// const t = useTranslations('home');
// t('title');
const sourceFiles = [
{
reference: null,
name: 'locales/en-US/home.json',
content: { title: 'Home' }
}
];
const result = await checkUndefinedKeys(
sourceFiles,
['src/**/*.tsx'],
{ format: 'next-intl', checks: ['undefined'] }
);
// {} - 'title' is defined
```
--------------------------------
### Check Undefined Keys with i18next Format
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-undefined-keys.md
This example demonstrates checking for undefined translation keys using the i18next format. It assumes a typical i18next setup with namespaced JSON files.
```typescript
// Code:
// import { useTranslation } from 'i18next';
// const { t } = useTranslation();
// return
{t('newFeature.title')}
;
const sourceFiles = [
{
reference: null,
name: 'locales/en-US/common.json',
content: { greeting: 'Hello' }
}
];
const result = await checkUndefinedKeys(
sourceFiles,
['src/**/*.tsx'],
{ format: 'i18next', checks: ['undefined'] }
);
// {
// 'src/components/Feature.tsx': ['newFeature.title']
// }
```
--------------------------------
### Run only missing keys check
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--only` or `-o` option to specify a single check to run. This example runs only the `missingKeys` check.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -o missingKeys
```
--------------------------------
### Example TranslationFile Structures
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
Demonstrates creating TranslationFile objects. The 'reference' property is used for grouping related files, while 'null' indicates no specific grouping.
```typescript
const file: TranslationFile = {
reference: 'en-US',
name: 'locales/de-DE/common.json',
content: {
greeting: 'Hallo',
farewell: 'Auf Wiedersehen'
}
};
const multiFile: TranslationFile = {
reference: null,
name: 'locales/en-US.json',
content: {
greeting: 'Hello'
}
};
```
--------------------------------
### Run only unused keys check
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--only` or `-o` option to specify a single check to run. This example runs only the `unused` check.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -o unused
```
--------------------------------
### Run only undefined keys check
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--only` or `-o` option to specify a single check to run. This example runs only the `undefined` check.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -o undefined
```
--------------------------------
### i18next Context Separator Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Demonstrates how context is appended to a translation key using an underscore.
```typescript
t('key_context') // Context appended with underscore
```
--------------------------------
### Example ICU Messages
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Provides examples of various ICU message formats including basic, plural, select, nested, and date/time.
```typescript
// Basic
"greeting: {name}"
// Plural
"You have {count, plural, =0 {no items} one {# item} other {# items}}"
// Select
"The {item} is {status, select, active {available} inactive {unavailable}}"
// Nested
"Welcome {name}! You have {count, plural, one {# message} other {# messages}}"
// Date/Time
"Sent on {date, date, long} at {time, time, short}"
```
--------------------------------
### Exclude a mix of files and folders
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
The `--exclude` or `-e` option accepts a combination of files and folders. This example excludes a folder and a specific file.
```bash
yarn i18n:check --locales translations/folderExamples -s en-US -e translations/folderExamples/fr/* translations/messageExamples/it.json
```
--------------------------------
### Run missing and invalid keys checks
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--only` or `-o` option to specify multiple checks. This example runs both `missingKeys` and `invalidKeys` checks, which is the default behavior.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -o missingKeys invalidKeys
```
--------------------------------
### Run unused and undefined keys checks
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--only` or `-o` option to specify multiple checks. This example runs both `unused` and `undefined` checks.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -o unused undefined
```
--------------------------------
### Example InvalidTranslationEntry Object
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
Shows an example of an InvalidTranslationEntry, specifying the translation key and the reason for the validation failure.
```typescript
const entry: InvalidTranslationEntry = {
key: 'greeting',
msg: 'Missing element argument'
};
```
--------------------------------
### Run only invalid keys check
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--only` or `-o` option to specify a single check to run. This example runs only the `invalidKeys` check.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -o invalidKeys
```
--------------------------------
### Import All Types from @lingual/i18n-check
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
Import all available types from the library for use in your project. Ensure the library is installed.
```typescript
import type {
Translation,
CheckResult,
InvalidTranslationEntry,
InvalidTranslationsResult,
TranslationFile,
FileInfo,
Options,
Context
} from '@lingual/i18n-check';
```
--------------------------------
### i18next Hook Usage Examples
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Demonstrates common ways to use the `useTranslation` and `withTranslation` hooks to access the translation function `t`.
```typescript
const { t } = useTranslation();
const { t } = useTranslation('namespace');
const { t } = withTranslation()(Component);
```
--------------------------------
### Example Translation Object
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
Illustrates the structure of a Translation object, showing nested keys and various value types.
```typescript
const translation: Translation = {
greeting: 'Hello',
farewell: 'Goodbye',
count: 42,
nested: {
key: 'value'
}
};
```
--------------------------------
### Custom Parser Component Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/configuration.md
Example of a custom component that wraps the i18next Trans component. This component can be recognized by the --parser-component-functions option.
```tsx
// Wraps Trans component
function MyTransComponent(props) {
return ;
}
// Will be recognized with:
// --parser-component-functions MyTransComponent
```
--------------------------------
### i18next Plural Handling Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Illustrates how i18next uses suffixes for plural forms and how to reference them dynamically. The parser normalizes these to a single base key.
```typescript
// Code
const count = 5;
return t(`items_${count === 1 ? 'one' : 'other'}`, { count });
// Normalized to single key reference: 'items'
```
--------------------------------
### i18next Function Call Examples
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Shows different ways to call the `t` function for retrieving translations, including with and without namespaces, and with interpolation arguments.
```typescript
t('translation.key')
t('namespace:translation.key')
t('translation_one', { count: 1 })
t('translation_other', { count: 2 })
```
--------------------------------
### Custom Component Functions for i18next
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-undefined-keys.md
This example demonstrates how to configure checkUndefinedKeys to recognize translation keys used within custom component wrappers for the i18next format.
```typescript
// Code:
//
const result = await checkUndefinedKeys(
sourceFiles,
['src/**/*.tsx'],
{ format: 'i18next', checks: ['undefined'] },
['MyCustomTransWrapper']
);
```
--------------------------------
### GitHub Actions workflow for i18n-check
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
A sample GitHub Actions workflow to automate i18n-check. This workflow installs dependencies, builds the project, and runs the i18n-check command, failing the action if issues are found.
```yaml
name: i18n Check
on:
pull_request:
branches:
- main
push:
branches:
- main
jobs:
i18n-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: yarn install & build
run: |
yarn install
yarn build
- name: yarn i18n-check
run: |
yarn i18n-check --locales translations/messageExamples --source en-US
```
--------------------------------
### Check unused and undefined keys with next-intl
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--unused` or `-u` option to find keys present in translation files but not in the codebase, and vice-versa. Requires specifying the `--format` option. This example uses `next-intl`.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -u client/ -f next-intl
```
--------------------------------
### Migrate from Deprecated --check Option
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
The --check option is deprecated and has been replaced by --only or -o. This example shows the migration path from the old to the new option.
```bash
i18n-check --locales -s --check
```
```bash
# Old (deprecated)
i18n-check --locales translations/ -s en-US --check missingKeys
# New (use --only instead)
i18n-check --locales translations/ -s en-US -o missingKeys
```
--------------------------------
### i18next Parser Validation Examples
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Illustrates valid and invalid translation scenarios based on structure, variable presence, plural forms, and tag names.
```typescript
// Valid - same structure
source: "You have {{count}} items"
target: "You haben {{count}} Artikel"
```
```typescript
// Invalid - missing variable
source: "Hello {{name}}"
target: "Hallo"
```
```typescript
// Valid - different plural forms (German has more forms)
source: "{count} items_one, {count} items_other"
target: "{count} items_zero, {count} items_one, {count} items_few"
```
```typescript
// Invalid - wrong tag name
source: "Click here"
target: "Klicken hier"
```
--------------------------------
### Example CheckResult Object
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
Demonstrates a CheckResult object, mapping locale identifiers to arrays of translation keys that require attention.
```typescript
const result: CheckResult = {
'de-de': ['missing_key_1', 'missing_key_2'],
'fr-fr': ['missing_key_1'],
'es-es': []
};
```
--------------------------------
### Check unused and undefined keys with i18next
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--unused` or `-u` option to find keys present in translation files but not in the codebase, and vice-versa. Requires specifying the `--format` option. This example uses `i18next`.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -u client/ -f i18next
```
--------------------------------
### Check unused and undefined keys with react-intl
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--unused` or `-u` option to find keys present in translation files but not in the codebase, and vice-versa. Requires specifying the `--format` option. This example uses `react-intl`.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -u client/ -f react-intl
```
--------------------------------
### Integrate i18n-check into TypeScript Build
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Incorporate i18n-check into your TypeScript build process. This example shows how to call the CLI tool from a build script, throwing an error if validation fails. This ensures that translations are checked before the build proceeds.
```typescript
// build.ts - include in your build script
import { execSync } from 'child_process';
const checkTranslations = () => {
try {
execSync(
'i18n-check --locales translations/ -s en-US -f i18next',
{ stdio: 'inherit' }
);
} catch {
throw new Error('Translation validation failed');
}
};
// Run check before build
checkTranslations();
console.log('Building application...');
```
--------------------------------
### Exclude multiple folders
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--exclude` or `-e` option to exclude specific files or folders from checks. This example excludes files from multiple folders using wildcards.
```bash
yarn i18n:check --locales translations/folderExamples -s en-US -e translations/folderExamples/fr/* translations/folderExample/it/*
```
--------------------------------
### Exclude multiple files
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--exclude` or `-e` option to exclude specific files or folders from checks. This example excludes multiple JSON files.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -e translations/messageExamples/fr-fr.json translations/messageExamples/de-at.json
```
--------------------------------
### Check Unused Keys with i18next Format
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-unused-keys.md
Example of using checkUnusedKeys with the 'i18next' format. This format parses TypeScript/JavaScript for hook calls, function calls, and component usage.
```typescript
// Code contains:
// const { t } = useTranslation();
// return
{t('greeting')}
;
const result = await checkUnusedKeys(
translationFiles,
['src/**/*.tsx'],
{ format: 'i18next', checks: ['unused'] }
);
// { 'locales/en-US.json': ['farewell', 'unused'] }
```
--------------------------------
### next-intl useTranslations Hook
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Examples of using the useTranslations hook to get a translation function, with and without a namespace.
```typescript
const t = useTranslations();
t('key')
```
```typescript
const t = useTranslations('namespace');
t('key')
```
```typescript
// Type alias
type TFunction = ReturnType;
const fn = (t: TFunction) => t('key');
```
--------------------------------
### Show Help Message
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Displays the help message, listing all available command-line options. Use either the long or short flag.
```bash
i18n-check --help
i18n-check -h
```
--------------------------------
### Build and Run i18n-check
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Build the project using 'pnpm run build' before running any of the following commands. These commands are used to check translations based on different configurations.
```bash
node dist/bin/index.js --locales translations/messageExamples -s en-US
```
```bash
node dist/bin/index.js --locales translations/flattenExamples -s en-US
```
```bash
node dist/bin/index.js --locales translations/i18NextMessageExamples -s en-US -f i18next
```
```bash
node dist/bin/index.js --locales translations/folderExample -s en-US
```
```bash
node dist/bin/index.js --locales translations/multipleFilesFolderExample/ -s en-US
```
```bash
node dist/bin/index.js --locales translations/folderExample,translations/messageExamples -s en-US
```
--------------------------------
### Select Form Syntax
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Demonstrates branching based on selected values with arbitrary option keys.
```icu
{gender, select, male {he} female {she} other {they}}
```
--------------------------------
### Run i18n-check Tests
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Execute the project's test suite using the provided pnpm command.
```bash
pnpm test
```
--------------------------------
### Basic i18n-check usage with source and locales
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Run i18n-check specifying the source locale and the directory containing translation files.
```bash
yarn i18n:check -s en-US --locales translations/
```
--------------------------------
### CheckResult Type Definition and Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-unused-keys.md
Defines the CheckResult type, which is a record of unused keys per translation file, or undefined. An example illustrates the expected output format.
```typescript
type CheckResult = Record | undefined;
// Example: { 'locales/en-US.json': ['unused_key_1', 'unused_key_2'] }
```
--------------------------------
### i18n-check with locales and source specified
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Run i18n-check specifying the locales directory and the source locale. This is a common configuration.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US
```
--------------------------------
### Example Usage of CheckError
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
Demonstrates catching a CheckError and accessing its location properties.
```typescript
try {
checkInvalidTranslations(source, targets);
} catch (error) {
if (error instanceof CheckError) {
console.error(error.message);
if (error.location) {
console.log(
`Error at line ${error.location.start.line}, ` +
`column ${error.location.start.column}`
);
}
}
}
```
--------------------------------
### React-intl FormattedMessage Component
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Examples of using the FormattedMessage component with different IDs, default messages, and values.
```jsx
```
```jsx
```
--------------------------------
### Basic Command Syntax
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
The fundamental structure for invoking the i18n-check command.
```bash
i18n-check [options]
```
--------------------------------
### Use summary reporter
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--reporter` or `-r` option to override standard error reporting. Passing `summary` prints a summary of missing or invalid keys.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -r summary
```
--------------------------------
### Example InvalidTranslationsResult
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/types.md
Illustrates the structure of an InvalidTranslationsResult, showing errors for specific locales. This is a typical output from validation functions.
```typescript
const result: InvalidTranslationsResult = {
'de-de': [
{ key: 'greeting', msg: 'Missing element argument' },
{ key: 'items', msg: 'Error in plural: Expected option "one"' }
],
'fr-fr': []
};
```
--------------------------------
### i18next Format - Tag Mismatch
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-invalid-translations.md
This example shows how to identify incorrect HTML tag usage in i18next formatted translations.
```APIDOC
## i18next Format - Tag Mismatch
### Description
This example shows how to identify incorrect HTML tag usage in i18next formatted translations.
### Method
`checkInvalidTranslations`
### Parameters
- **source** (object) - Required - The source translation object.
- **targets** (object) - Required - An object containing target language translations.
- **options** (object) - Optional - Configuration options, including `format: 'i18next'`.
### Request Example
```typescript
const source = {
richText: 'Click here'
};
const targets = {
'de-de': {
richText: 'Klicken hier' // Wrong tag name
}
};
const result = checkInvalidTranslations(
source,
targets,
{ format: 'i18next' }
);
```
### Response
#### Success Response (object)
An object containing validation results, detailing mismatches per language and key.
#### Response Example
```json
{
"de-de": [{
"key": "richText",
"msg": "Expected tag \"bold\" but received \"strong\""
}]
}
```
```
--------------------------------
### i18next Format - Variable Mismatch
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-invalid-translations.md
This example demonstrates how `checkInvalidTranslations` detects missing interpolation variables in i18next formatted translations.
```APIDOC
## i18next Format - Variable Mismatch
### Description
This example demonstrates how `checkInvalidTranslations` detects missing interpolation variables in i18next formatted translations.
### Method
`checkInvalidTranslations`
### Parameters
- **source** (object) - Required - The source translation object.
- **targets** (object) - Required - An object containing target language translations.
- **options** (object) - Optional - Configuration options, including `format: 'i18next'`.
### Request Example
```typescript
const source = {
greeting: 'Hello {{firstName}} {{lastName}}'
};
const targets = {
'de-de': {
greeting: 'Hallo {{firstName}}' // Missing {{lastName}}
}
};
const result = checkInvalidTranslations(
source,
targets,
{ format: 'i18next' }
);
```
### Response
#### Success Response (object)
An object containing validation results, detailing mismatches per language and key.
#### Response Example
```json
{
"de-de": [{
"key": "greeting",
"msg": "Error in interpolation: Expected lastName but received undefined"
}]
}
```
```
--------------------------------
### Verify Locale Directory and Files
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Troubleshoot 'No Translation Files Found' errors by verifying the path to your locale directory and ensuring files exist for the specified source locale.
```bash
# Verify locale directory path
ls translations/
# Check that files match source locale identifier
ls translations/ | grep en-US
```
--------------------------------
### Configure i18n Check for Unused/Undefined Keys
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Ensure that source code analysis for unused or undefined keys is correctly configured. This requires specifying the format, the source directory for analysis, and the types of keys to report.
```bash
# Ensure:
# 1. --format is specified (required for source code analysis)
# 2. --unused with source paths is provided
# 3. --only includes 'unused' and/or 'undefined'
i18n-check \
--locales translations/ \
--source en-US \
--format i18next \
--unused src/ \
--only unused undefined
```
--------------------------------
### Basic checkTranslations() Usage
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-translations.md
Demonstrates the basic usage of checkTranslations with source and target files to find missing keys.
```typescript
import { checkTranslations } from '@lingual/i18n-check';
const sourceFiles = [
{
reference: 'en-US',
name: 'locales/en-US/common.json',
content: { greeting: 'Hello', farewell: 'Goodbye' }
}
];
const targetFiles = [
{
reference: 'en-US',
name: 'locales/de-DE/common.json',
content: { greeting: 'Hallo' } // missing 'farewell'
}
];
const result = checkTranslations(sourceFiles, targetFiles);
// result.missingKeys = { 'locales/de-DE/common.json': ['farewell'] }
```
--------------------------------
### React-intl with Source Code Analysis
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Checks react-intl format translations by analyzing source code for unused and undefined keys. Specify source file patterns for analysis.
```bash
# react-intl format checking unused and undefined keys
i18n-check \
--locales locales/ \
--source en-US \
--format react-intl \
--unused "src/**/*.{tsx,ts}" \
--only unused undefined
```
--------------------------------
### React-intl defineMessages()
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Shows how to define messages using defineMessages and then format them using intl.formatMessage.
```typescript
const messages = defineMessages({
greeting: { id: 'app.greeting', defaultMessage: 'Hello' },
farewell: { id: 'app.farewell', defaultMessage: 'Goodbye' }
});
intl.formatMessage(messages.greeting)
```
--------------------------------
### Scan Source Code for Usage
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Use the --unused (or -u) option to provide paths for source code scanning to detect unused or undefined translation keys. This requires specifying a --format. It enables 'unused' and 'undefined' checks.
```bash
i18n-check --locales -s --unused -f
```
```bash
i18n-check -l -s -u [path2 ...] -f i18next
```
```bash
# Scan src directory with i18next
i18n-check --locales translations/ -s en-US \
-f i18next \
-u src/ \
-o unused
```
```bash
# Scan multiple directories
i18n-check --locales translations/ -s en-US \
-f react-intl \
-u src/ components/ \
-o unused undefined
```
```bash
# With glob patterns
i18n-check --locales translations/ -s en-US \
-f next-intl \
-u "src/**/*.{ts,tsx}" \
-o unused undefined
```
--------------------------------
### Check invalid translations with options
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use `checkInvalidTranslations` to find invalid keys in target files. This example includes options to specify the 'i18next' format for validation.
```typescript
import { checkInvalidTranslations } from '@lingual/i18n-check';
const options = {
format: 'i18next',
};
const result = checkInvalidTranslations(source, targets, options);
// {
// "de-de": ["invalid_translation_key", "some_other_invalid_translation_key"],
// "fr-fr": [],
// };
```
--------------------------------
### i18next Interpolation Syntax
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Demonstrates basic variable interpolation using double curly braces.
```plaintext
Hello {{name}}
```
--------------------------------
### Exclude a single file
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--exclude` or `-e` option to exclude specific files or folders from checks. This example excludes a single JSON file.
```bash
yarn i18n:check --locales translations/messageExamples -s en-US -e translations/messageExamples/fr-fr.json
```
--------------------------------
### i18next Format - Variable Mismatch Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-invalid-translations.md
Shows how to identify missing interpolation variables in i18next formatted translations. This check is enabled by setting the format option to 'i18next'.
```typescript
const source = {
greeting: 'Hello {{firstName}} {{lastName}}'
};
const targets = {
'de-de': {
greeting: 'Hallo {{firstName}}' // Missing {{lastName}}
}
};
const result = checkInvalidTranslations(
source,
targets,
{ format: 'i18next' }
);
// {
// 'de-de': [{
// key: 'greeting',
// msg: 'Error in interpolation: Expected lastName but received undefined'
// }]
// }
```
--------------------------------
### Check translations with custom options
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `checkTranslations` function to validate source and target locales. This example demonstrates setting the format to 'i18next' for specific validation rules.
```typescript
import { checkTranslations } from '@lingual/i18n-check';
const options = {
format: 'i18next',
};
const { invalidKeys, missingKeys } = checkTranslations(
source,
targets,
options
);
```
--------------------------------
### Run i18n-check directly via node_modules
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Execute the i18n-check command directly from the local node_modules/.bin directory.
```bash
node_modules/.bin/i18n-check
```
--------------------------------
### Scan Source Code for Unused Keys
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/configuration.md
Use the --unused or -u flag to specify source code paths for scanning translation key usage. This option requires a --format to be specified and enables 'unused' and 'undefined' checks. Glob patterns are accepted.
```bash
i18n-check --locales translations/ -s en-US -u src/ -f i18next
i18n-check --locales translations/ -s en-US -u src/ components/ -f react-intl
```
--------------------------------
### Invalid Translation: Wrong Element Type
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/errors.md
This error occurs when the element types in the source and target translations do not match. For example, the source has a plural element, but the target has a simple argument.
```typescript
// Source: count: '{count, plural, one {item} other {items}}'
// Target: count: '{count}'
// Error: Expected element of type "plural" but received "argument"
```
--------------------------------
### ICU Format - Argument Mismatch Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-invalid-translations.md
Demonstrates how to use checkInvalidTranslations to detect missing variables in ICU formatted translations. Ensure all source variables are present in target translations.
```typescript
import { checkInvalidTranslations } from '@lingual/i18n-check';
const source = {
greeting: 'Hello {name}'
};
const targets = {
'de-de': { greeting: 'Hallo' } // Missing {name} variable
};
const result = checkInvalidTranslations(source, targets);
// {
// 'de-de': [{
// key: 'greeting',
// msg: 'Missing element argument'
// }]
// }
```
--------------------------------
### Module Organization in i18n-check
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/README.md
Illustrates the directory structure and main modules of the i18n-check project. Useful for understanding the codebase organization.
```tree
src/
├── index.ts # Main API entry point
├── types.ts # Type definitions
├── errorReporters.ts # CLI output formatting
├── bin/
│ └── index.ts # CLI entry point
└── utils/
├── findMissingKeys.ts # Missing key detection
├── findInvalidTranslations.ts # ICU format validation
├── findInvalidI18NextTranslations.ts # i18next validation
├── flattenTranslations.ts # Object flattening
├── i18NextParser.ts # i18next message parser
├── i18NextSrcParser.ts # i18next source code analyzer
├── nextIntlSrcParser.ts # next-intl source analyzer
└── constants.ts # Constants (plural suffixes)
```
--------------------------------
### i18next Nesting Syntax
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/format-parsers.md
Demonstrates nesting of translation keys using `$t()` or the nesting operator.
```plaintext
Save {{defaultSave}} or load a {{loadData}}
```
```plaintext
Level 1: $t(level2.key)
```
```plaintext
Title: $t(nsWithFeature) items
```
--------------------------------
### ICU Format - Plural Mismatch Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-invalid-translations.md
Illustrates detecting missing plural cases in ICU formatted translations. The checker verifies that all plural options defined in the source exist in the target.
```typescript
const source = {
items: '{count, plural, one {# item} other {# items}}'
};
const targets = {
'de-de': {
items: '{count, plural, one {# artikel}}'
// Missing 'other' case
}
};
const result = checkInvalidTranslations(source, targets);
// {
// 'de-de': [{
// key: 'items',
// msg: 'Error in plural: Expected option "other" but missing'
// }]
// }
```
--------------------------------
### i18n-check with i18next format
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Run i18n-check specifying the source locale, locales directory, and the i18next format for validation.
```bash
yarn i18n:check --locales translations/i18NextMessageExamples -s en-US -f i18next
```
--------------------------------
### Exclude a single folder
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use the `--exclude` or `-e` option to exclude specific files or folders from checks. This example excludes all files within a specific folder using a wildcard.
```bash
yarn i18n:check --locales translations/folderExamples -s en-US -e translations/folderExamples/fr/*
```
--------------------------------
### i18next Format - Tag Mismatch Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-invalid-translations.md
Demonstrates detecting incorrect HTML tag names in i18next formatted translations. The checker ensures that opening and closing tags match between source and target.
```typescript
const source = {
richText: 'Click here'
};
const targets = {
'de-de': {
richText: 'Klicken hier' // Wrong tag name
}
};
const result = checkInvalidTranslations(
source,
targets,
{ format: 'i18next' }
);
// {
// 'de-de': [{
// key: 'richText',
// msg: 'Expected tag "bold" but received "strong"'
// }]
// }
```
--------------------------------
### Next-intl Type Alias Example
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/configuration.md
Demonstrates how to use a type alias for the return type of next-intl's useTranslations. The parser needs the alias name specified via --next-intl-translation-fn-type-alias to recognize translation calls.
```typescript
// Without type alias (always recognized):
const t = useTranslations('home');
const text = t('title');
// With type alias (needs --next-intl-translation-fn-type-alias):
type TFunction = ReturnType;
const indirectCall = (t: TFunction) => {
return t('title');
};
// Use: --next-intl-translation-fn-type-alias TFunction
```
--------------------------------
### Add i18n:check script to package.json
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Define a package.json script to easily run the i18n-check command.
```json
"scripts": {
// ...other commands,
"i18n:check": "i18n-check"
}
```
--------------------------------
### i18n-check with Single Locale Folder
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Configure i18n-check to process locales from a single directory using the --locales option. Specify the base/reference file with the -s or --source option for comparison.
```bash
yarn i18n:check --locales locales -s locales/en-us.json
```
--------------------------------
### Basic API Options Object
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/configuration.md
A fundamental configuration object for programmatic use. Specify the format, checks to perform, and patterns to ignore.
```typescript
const options: Options = {
format: 'i18next',
checks: ['missingKeys', 'invalidKeys'],
ignore: ['beta.feature.*']
};
```
--------------------------------
### Check Unused Keys with react-intl Format
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/api-reference/check-unused-keys.md
Demonstrates how to use checkUnusedKeys for the 'react-intl' format. Ensure translation files and source files are correctly specified.
```typescript
import { checkUnusedKeys } from '@lingual/i18n-check';
const translationFiles = [
{
reference: null,
name: 'locales/en-US.json',
content: {
greeting: 'Hello',
farewell: 'Goodbye',
unused: 'This key is not used'
}
}
];
const filesToParse = ['src/**/*.tsx', 'src/**/*.ts'];
const result = await checkUnusedKeys(
translationFiles,
filesToParse,
{ format: 'react-intl', checks: ['unused'] }
);
// { 'locales/en-US.json': ['unused'] }
```
--------------------------------
### TypeScript Example with ReturnType for Indirect Function Calls
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
This TypeScript code demonstrates an indirect function call where the translation function type is inferred using ReturnType. This is a standard way to handle translations within components.
```typescript
const indirectFnCall = (
t: ReturnType>
) => {
const indirectTranslation = t('someKey');
// Do something with the indirectTranslation
};
```
--------------------------------
### Run i18n-check CLI with multiple folders
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
Use this command to check locales across multiple specified folders. The `-l` flag indicates the folders containing locales, and `-s` specifies the source locale directory.
```bash
yarn i18n:check -l spaceOne spaceTwo -s en-US
```
--------------------------------
### Run i18n-check in Node.js Script
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Execute i18n-check as a child process within a Node.js script. This is useful for integrating translation checks directly into your application's workflow or build scripts. Ensure 'i18n-check' is installed globally or locally.
```javascript
// Run i18n-check via child process
const { execSync } = require('child_process');
try {
execSync('i18n-check --locales translations/ -s en-US', {
stdio: 'inherit'
});
console.log('✓ All translations valid');
} catch (error) {
console.error('✗ Translation validation failed');
process.exit(1);
}
```
--------------------------------
### Run CLI Validation
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/README.md
Use the CLI for CI/CD pipelines, pre-commit hooks, or one-off validation runs. Specify the locales directory, source locale, and format parser.
```bash
i18n-check --locales translations/ -s en-US -f i18next
```
--------------------------------
### TypeScript Example with Next-Intl Type Alias for Indirect Function Calls
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
This TypeScript code shows how to handle indirect function calls in a next-intl codebase when a type alias is used for the translation function. The --next-intl-translation-fn-type-alias option in i18n-check can be configured to recognize these aliases.
```typescript
import { NextIntlTranslateFnAlias } from './types';
const indirectFnCall = (t: NextIntlTranslateFnAlias<'SomeNameSpace'>) => {
const indirectTranslation = t('someKey');
// Do something with the indirectTranslation
};
```
--------------------------------
### Specify Allowed i18n Formats
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/cli-reference.md
Use the '-f' or '--format' flag to specify the translation file format. This is crucial for source code analysis features like detecting unused or undefined keys.
```bash
# Use only allowed formats
-f icu # Default
-f i18next # For i18next library
-f react-intl # For react-intl
-f next-intl # For next-intl
```
--------------------------------
### Check Missing Keys Only
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/configuration.md
Use this command to find only the translation keys that are missing in the specified locales. Ensure the locales directory and source locale are correctly set.
```bash
i18n-check --locales translations/ -s en-US -o missingKeys
```
--------------------------------
### i18n-check with Folders Per Locale
Source: https://github.com/lingualdev/i18n-check/blob/main/README.md
When locales are organized in subfolders, each containing a single locale file, specify the parent directory with --locales and the source locale folder name with -s. The tool will automatically find corresponding files.
```bash
yarn i18n:check --locales locales -s en-US
```
--------------------------------
### Check All Formats with Ignored Keys
Source: https://github.com/lingualdev/i18n-check/blob/main/_autodocs/configuration.md
This command performs a comprehensive check including missing and invalid keys, while ignoring specific keys or patterns. Use the -i flag for patterns or exact key names to exclude from the check.
```bash
i18n-check --locales translations/ -s en-US \
-i "features.beta.*" "internal.admin" \
-o missingKeys invalidKeys
```