npm install i18n-trivial --save-dev
Here's an example, You can also clone this project and run npm run dev
import { i18n, I18nProvider, useI18n, withTranslation } from "i18n-trivial";
You need to execute i18n.use(config)
before the root component render
- languageOptions?: Record<string, string>;
- initialLanguage?: string;
- initialNamespace?: string;
- cache?: Record<string, any>;
i18n.use({
languageOptions: {
en: '英语',
cn: '中文',
},
initialLanguage: 'cn',
initialNamespace: 'common',
cache: {
en: require('./locales/en.json'),
cn: require('./locales/cn.json'),
},
})
Note: You can set the parameter '?lang=cn' at the end of the URL, indicating that the current default language is Chinese. The 'initialLanguage' will be automatically detected. If not specified, it will default to the browser's language. If the specified language doesn't exist, you will receive a warning.
You need to wrap the project root component with the <I18nProvider>
<I18nProvider>
<App />
</I18nProvider>
function App() {
const { t, changeLanguage, currentLanguage } = useI18n(namespace?)
return (
<div className="App">
{t("name")}
</div>
);
}
export default App;
function App({ t }) {
return (
<div className="App">
{t("name")}
</div>
);
}
export default withTranslation(App, namespace?);
Note: If you configured initialNamespace, this property will be read automatically when using withTranslation
{t("address", { city: "xian" })}
{t('apples', {_count: 3})}
- key: string
- payload?: any
Please follow the format below to create the translation file, please note that common
is a namespace, you can also ignore this parameter, if you do not want to use the namespace, and _count
is a unique attribute, used to do simple and complex, do not use other
{
"common": {
"name": "yixiang",
"address": "i'm in {city}",
"apples": {
"one": "{_count} apple",
"other": "{_count} apples"
}
}
}
{
"name": "yixiang",
"address": "city: {city}"
}
Please submit a pull request to me