This is a CLI that helps to make type safe translations in your typescript projects. Keep in mind this project is experimental, It assumes that you have a very specific structure for your translations.
yarn add -D i18n-codegen
In this early stage, this package assume you have your translations in a JSON file using nested format.
{
"home": {
"title": "Title",
"subtitle": "Subtitle"
},
"info": {
"title": "More info",
"features": {
"first": "First Feature",
"second": "Second Feature"
}
}
}
export const I18nKeys = [
'home.title',
'home.subtitle',
'info.title',
'info.features.first',
'info.features.second',
] as const;
export type I18nKey = typeof I18nKeys[number];
module.exports = {
// Your main translation file
translationsFilePath: './src/locales/en_US.json',
// Output of the generated types
outputFilePath: './src/generated/i18n-types.ts',
};
The --watch
mode is optional
{
"scripts": {
"i18n": "i18n-codegen generate --watch"
}
}
Create a wrapper on top of useTranslation
hook.
import {
UseTranslationOptions,
useTranslation as __useTranslation,
} from 'react-i18next';
import { I18nKey } from './generated/i18n-types';
export function useTranslation() {
const { t: __t, i18n } = __useTranslation();
const t = (key: I18nKey, options?: UseTranslationOptions) =>
__t(key, options);
return { t, i18n };
}
Now you can enjoy type safety in your translation keys!
import React from 'react';
import { View, Text } from 'react-native';
import { useTranslation } from "./i18n/useTranslation";
export const MyComponent = () => {
const { t } = useTranslation()
return (
<View>
<Text>{t('home.title')}</Title>
</View>
)
}
- ✅ Setup releases
- Lint file after generate with prettier settings
- Init command
- Validation of config file
- Generate react hook automatically
This project was bootstrapped with TSDX.
Below is a list of commands you will probably find useful.
Runs the project in development/watch mode. Your project will be rebuilt upon changes. TSDX has a special logger for you convenience. Error messages are pretty printed and formatted for compatibility VS Code's Problems tab.
Your library will be rebuilt if you make edits.
Bundles the package to the dist
folder.
The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).
Runs the test watcher (Jest) in an interactive mode. By default, runs tests related to files changed since the last commit.