mobx-i18n
v0.5.0
Published
Responsive Translation utility based on TypeScript & MobX
Downloads
64
Maintainers
Readme
MobX i18n
Responsive Translation utility based on TypeScript & MobX
Features
- [x] Type hinting of Text keys
- [x] Lambda Expression values
- [x] Space utility for CJK & other characters
- [x] Responsive re-rendering
- [x] Async loading of Language packages
- [x] support HTTP protocol for Server-side rendering
- [x] support BOM/DOM language API for Client-side rendering
Versions
| SemVer | branch | status | ES decorator | MobX |
| :-------: | :------: | :----------: | :----------: | :---------: |
| >=0.5.0
| main
| ✅developing | stage-3 | >=6.11
|
| <0.5.0
| master
| ❌deprecated | stage-2 | >=4 <6.11
|
React/Next.js example
Original from https://github.com/kaiyuanshe/kaiyuanshe.github.io
Installation
npm i mobx mobx-react mobx-i18n
Configuration
tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"useDefineForClassFields": true,
"experimentalDecorators": false
}
}
Translation
translation/zh-CN.ts
import { textJoin } from 'mobx-i18n';
export default {
open_source: '开源',
project: '项目',
love: ({ a, b }: Record<'a' | 'b', string>) => textJoin(a, '爱', b)
} as const;
translation/en-US.ts
import { textJoin } from 'mobx-i18n';
export default {
open_source: 'Open Source',
project: 'project',
love: ({ a, b }: Record<'a' | 'b', string>) => textJoin(a, 'love', b)
} as const;
Initialization
model/Translation.ts
export const i18n = new TranslationModel({
'zh-CN': zhCN,
'en-US': () => import('../translation/en-US')
});
export const LanguageName: Record<(typeof i18n)['currentLanguage'], string> = {
'zh-CN': '简体中文',
'en-US': 'English'
};
pages/index.ts
import { GetServerSideProps } from 'next';
import { textJoin, parseLanguageHeader } from 'mobx-i18n';
import { i18n, LanguageName } from 'model/Translation';
export const getServerSideProps: GetServerSideProps = ({ req }) => {
const languages = parseLanguageHeader(req.headers['accept-language'] || '');
await i18n.loadLanguages(languages);
return { props: {} };
};
@observer
export default class HomePage extends PureComponent {
render() {
const { currentLanguage, t } = i18n;
return (
<>
<select
value={currentLanguage}
onChange={({ currentTarget: { value } }) =>
i18n.changeLanguage(value as typeof currentLanguage)
}
>
{Object.entries(LanguageName).map(([code, name]) => (
<option key={code} value={code}>
{name}
</option>
))}
</select>
<p>
{t('love', {
a: '我',
b: textJoin(t('open_source'), t('project'))
})}
</p>
</>
);
}
}
Inspired by
- https://github.com/infinum/react-mobx-translatable
- https://github.com/jverhoelen/react-mobx-i18n
- https://github.com/QuiiBz/next-international