@ackee/jerome 中文文档教程
Jerome
本地化模块主要用于 Ackee 的前端开发。
包名指的是Saint Jerome所有翻译者的赞助人。
Table of contents
Installation
使用纱线:
yarn add @ackee/jerome
使用 npm:
npm i -s @ackee/jerome
Usage
所有部分都是独立的,但最好一起工作。 不要忘记,为了正确使用选择器,您的 reducer 必须使用 translate
键存储(如示例所示)。
Used APIs
杰罗姆使用 react-intl@3
依赖于一些本机浏览器 API 因此,如果您打算将组件用于复数或相对时间格式,请确保您的最小支持浏览器实现这些 API 或使用 polyfill,如所述波纹管
对于 polyfilling 复数,使用 intl-pluralrules
包。
if (!Intl.PluralRules) {
require('intl-pluralrules');
}
对于填充复数,请使用 intl-relativetimeformat
包。
if (!Intl.RelativeTimeFormat) {
require('@formatjs/intl-relativetimeformat/polyfill');
require('@formatjs/intl-relativetimeformat/dist/locale-data/de'); // Add locale data for de
}
API
Components
Translatable
- It wraps
children
withIntlProvider
fromreact-intl
. TheIntlProvider
receives currentlocale
from redux store. - It dispatches
SET_INTL
action everytime thelocale
changes. This is required to make [getIntl
] saga work. See createIntlContext for more info.
⚠️
为了让它顺利运行,你必须只安装一次react-intl
! 所以要确保你的依赖结构是扁平的。
import { Translatable } from '@ackee/jerome';
const messages = {
cs: {
hello: 'Dobry den',
...
},
en: {
hello: 'Hello',
...
},
};
export function Localizations({ children }) {
return <Translatable intlMessages={messages}>{children}</Translatable>
}
HOC
要使 HOC 正常工作,您必须只安装一次 react-intl
! 所以要确保你的依赖结构是扁平的。
[Deprecated]translatableFactory(intlLocaleData): (ContentComponent) => TranslatableContentComponent
它提供 reac-intl
本地化上下文,因此您首先必须向将返回实际 HOC 的工厂提供本地化消息。
intlLocaleData
- 包含由语言环境名称键入的消息的对象,例如。
const messages = {
cs: {
hello: 'Dobry den',
...
},
en: {
hello: 'Hello',
...
},
}
工厂返回接收 ContentComponent
的函数,并用 IntlProvider 包装返回它从 store.translate.locale
存储路径。
示例
import { FormattedMessage, addLocaleData } from 'react-intl';
import { translatableFactory } from '@ackee/jerome';
const ContentComponent = () => (
<div id="app">
<h1><FormattedMessage id="hello" /></h1>
<h2><FormattedMessage id="bye.instant" /></h2>
<h3><FormattedMessage id="bye.forever" /></h3>
</div>
);
const messages = {
cs: {
hello: 'Cau',
'bye.instant': 'Nashledanou',
'bye.forever': 'Sbohem',
},
en: {
hello: 'Hello',
'bye.instant': 'See you later',
'bye.forever': 'Goodbye',
},
};
const store = createStore((state = initialState) => ({
translate: { locale: 'cs' },
}));
TranslatableComponent = translatableFactory(messages)(ContentComponent);
ReactDOM.render(<TranslatableComponent store={store} />, document.getElementById('app'));
translatableFactory(intlLocaleData, antdLocaleData): (ContentComponent) => TranslatableContentComponent
translatableFactory
的重载用于Ant design组件库。 它通过添加 antd
本地化上下文扩展了标准 translatableFactory
,但您必须提供 antLocaleData
作为工厂的第二个参数。
intlLocaleData
- 以语言环境名称为键的 antd 语言环境对象。 例如。
import cs_CZ from 'antd/lib/locale-provider/cs_CZ';
import en_US from 'antd/lib/locale-provider/en_US';
const messages = {
cs: cs_CZ,
en: en_US,
}
用法和translatableFactory
几乎一样,你只需要从@ackee/jerome/antd导入它
而不是 @ackee/jerome
。
import { FormattedMessage, addLocaleData } from 'react-intl';
import { Pagination } from 'antd';
import cs_CZ from 'antd/lib/locale-provider/cs_CZ';
import en_US from 'antd/lib/locale-provider/en_US';
import { translatableFactory } from '@ackee/jerome/antd'; // notice the import path
const ContentComponent = () => (
<div id="app">
<h1><FormattedMessage id="hello" /></h1>
<Pagination defaultCurrent={1} total={50} showSizeChanger />
</div>
);
const messages = {
cs: {
hello: 'Cau',
},
en: {
hello: 'Hello',
},
};
const antdMessages = {
cs: cs_CZ,
en: en_US,
}
const store = createStore((state = initialState) => ({
translate: { locale: 'cs' },
}));
// provide antd messages as a second argument
TranslatableComponent = translatableWithAntdFactory(messages, antdMessages)(ContentComponent);
ReactDOM.render(<TranslatableComponent store={store} />, document.getElementById('app'));
Actions
setLocale(locale: string)
示例
import { setLocale } from '@ackee/jerome';
dispatch(setLocale('cs'));
getLocale
示例
import { getLocale } from '@ackee/jerome';
dispatch(getLocale());
Action types
import { actionTypes } from '@ackee/jerome'
Reducer
Reducer 实际上是reducer 工厂,因为您必须首先提供默认语言环境。
reducer(locale: string): TranslateReducer
示例
import { reducer as translateFactory } from '@ackee/jerome';
const translate = translateFactory('cs');
const appReducers = combineReducers({
translate,
...
});
Selectors
translateSelector(state: State): { locale: string }
选择商店的翻译
部分。
示例
import { translateSelector } from '@ackee/jerome';
translateSelector(state); // { locale: 'cs' }
Sagas
saga()
传奇有两个目的,都与处理语言环境的持久存储有关。
- It saves locale on every
SET_LOCALE
action into the persistent storage. - It loads locale from persistent storage when app load and set it up.
示例
import { saga as localization } from '@ackee/jerome';
const rootSaga = function* () {
yield all([
localization(), // plug it into root saga
...
]);
};
function configureStore(initialState) {
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
const middleware = applyMiddleware(...middlewares);
const store = createStore(reducer, initialState, enhancer);
sagaMiddleware.run(rootSaga);
return store;
}
createIntlContext
createIntlContext
是一个辅助函数,用于创建 getIntl
saga 使用的特定上下文形状。 由于 redux-saga 上下文的限制,此上下文必须由该库的用户在应用程序的最顶层传奇中设置:
import { setContext, all } from 'redux-saga/effects';
import { createIntlContext } from '@ackee/jerome';
function * rootSaga() {
yield setContext(createIntlContext());
yield all([
.... sagas using getIntl()
])
}
sagaMiddleware.run(rootSaga);
如果没有设置上下文,getIntl
saga 将返回 null
即使库的其余部分被正确使用。
getIntl(): IntlShape
getIntl
saga 返回一个与 intlShape< 完全对应的 intl 对象/代码>
。 saga 依赖于 createIntlContext
Example
import { getIntl } from '@ackee/jerome';
function* mySaga() {
const intl = yield getIntl();
const translatedMessage = intl.formatMessage({
id: 'hello'
});
}
Utilities
saveLocale(locale: string)
的正确使用,用于区域设置的持久存储。
示例
import { saveLocale } from '@ackee/jerome';
saveLocale('cs');
loadLocale(): string
用于从持久存储中获取语言环境设置。
示例
import { loadLocale } from '@ackee/jerome';
loadLocale(); // 'cs'
localStorageHandlers
涵盖了上述两个实用程序。
例子
import { localStorageHandlers } from '@ackee/jerome';
localStorageHandlers.saveLocale('en');
localStorageHandlers.loadLocale(); // 'en'
Jerome
Localization module useful mainly for frontend development in Ackee.
Name of package refers to Saint Jerome the patron of all translators.
Table of contents
Installation
Using yarn:
yarn add @ackee/jerome
Using npm:
npm i -s @ackee/jerome
Usage
All parts are independent, but best works all together. Don't forget that for correct usage of selectors your reducer have to be stored with translate
key (as in example).
Used APIs
Jerome uses react-intl@3
which relies on some native browser APIs so if you're going to use components for plurals or relative time format, be sure that your minimal supported browsers implement those APIs or use polyfills as described bellow
For polyfilling plurals, use intl-pluralrules
package.
if (!Intl.PluralRules) {
require('intl-pluralrules');
}
For polyfilling plurals, use intl-relativetimeformat
package.
if (!Intl.RelativeTimeFormat) {
require('@formatjs/intl-relativetimeformat/polyfill');
require('@formatjs/intl-relativetimeformat/dist/locale-data/de'); // Add locale data for de
}
API
Components
Translatable
- It wraps
children
withIntlProvider
fromreact-intl
. TheIntlProvider
receives currentlocale
from redux store. - It dispatches
SET_INTL
action everytime thelocale
changes. This is required to make [getIntl
] saga work. See createIntlContext for more info.
⚠️
To make it work smoothly, you must havereact-intl
installed just once! So be sure your dependencies structure is flat.
import { Translatable } from '@ackee/jerome';
const messages = {
cs: {
hello: 'Dobry den',
...
},
en: {
hello: 'Hello',
...
},
};
export function Localizations({ children }) {
return <Translatable intlMessages={messages}>{children}</Translatable>
}
HOC
To make HOCs works properly, you must have react-intl
installed just once! So be sure your dependencies structure is flat.
[Deprecated]translatableFactory(intlLocaleData): (ContentComponent) => TranslatableContentComponent
It provides reac-intl
localization context, so you first have to provide localization messages to the factory that will return the actual HOC.
intlLocaleData
- object with messages keyed by locale name, eg.
const messages = {
cs: {
hello: 'Dobry den',
...
},
en: {
hello: 'Hello',
...
},
}
The factory returns function that receives ContentComponent
and return it wrapped with IntlProvider which receives locale from the store.translate.locale
store path.
Example
import { FormattedMessage, addLocaleData } from 'react-intl';
import { translatableFactory } from '@ackee/jerome';
const ContentComponent = () => (
<div id="app">
<h1><FormattedMessage id="hello" /></h1>
<h2><FormattedMessage id="bye.instant" /></h2>
<h3><FormattedMessage id="bye.forever" /></h3>
</div>
);
const messages = {
cs: {
hello: 'Cau',
'bye.instant': 'Nashledanou',
'bye.forever': 'Sbohem',
},
en: {
hello: 'Hello',
'bye.instant': 'See you later',
'bye.forever': 'Goodbye',
},
};
const store = createStore((state = initialState) => ({
translate: { locale: 'cs' },
}));
TranslatableComponent = translatableFactory(messages)(ContentComponent);
ReactDOM.render(<TranslatableComponent store={store} />, document.getElementById('app'));
translatableFactory(intlLocaleData, antdLocaleData): (ContentComponent) => TranslatableContentComponent
There is an overload of translatableFactory
for usage with Ant design components library. It extends standard translatableFactory
with adding antd
localization context, but you have to provide the antLocaleData
as a second argument to the factory.
intlLocaleData
- object with antd locales keyed by locale name. eg.
import cs_CZ from 'antd/lib/locale-provider/cs_CZ';
import en_US from 'antd/lib/locale-provider/en_US';
const messages = {
cs: cs_CZ,
en: en_US,
}
Usage is almost same as for the translatableFactory
, you only need to import it from @ackee/jerome/antd
instead of @ackee/jerome
.
import { FormattedMessage, addLocaleData } from 'react-intl';
import { Pagination } from 'antd';
import cs_CZ from 'antd/lib/locale-provider/cs_CZ';
import en_US from 'antd/lib/locale-provider/en_US';
import { translatableFactory } from '@ackee/jerome/antd'; // notice the import path
const ContentComponent = () => (
<div id="app">
<h1><FormattedMessage id="hello" /></h1>
<Pagination defaultCurrent={1} total={50} showSizeChanger />
</div>
);
const messages = {
cs: {
hello: 'Cau',
},
en: {
hello: 'Hello',
},
};
const antdMessages = {
cs: cs_CZ,
en: en_US,
}
const store = createStore((state = initialState) => ({
translate: { locale: 'cs' },
}));
// provide antd messages as a second argument
TranslatableComponent = translatableWithAntdFactory(messages, antdMessages)(ContentComponent);
ReactDOM.render(<TranslatableComponent store={store} />, document.getElementById('app'));
Actions
setLocale(locale: string)
Example
import { setLocale } from '@ackee/jerome';
dispatch(setLocale('cs'));
getLocale
Example
import { getLocale } from '@ackee/jerome';
dispatch(getLocale());
Action types
import { actionTypes } from '@ackee/jerome'
Reducer
Reducer is actually reducer factory since you must provide default locale first.
reducer(locale: string): TranslateReducer
Example
import { reducer as translateFactory } from '@ackee/jerome';
const translate = translateFactory('cs');
const appReducers = combineReducers({
translate,
...
});
Selectors
translateSelector(state: State): { locale: string }
Select translate
part of store.
Example
import { translateSelector } from '@ackee/jerome';
translateSelector(state); // { locale: 'cs' }
Sagas
saga()
The saga has two purposes, both related to handling persistent storing of locale.
- It saves locale on every
SET_LOCALE
action into the persistent storage. - It loads locale from persistent storage when app load and set it up.
Example
import { saga as localization } from '@ackee/jerome';
const rootSaga = function* () {
yield all([
localization(), // plug it into root saga
...
]);
};
function configureStore(initialState) {
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
const middleware = applyMiddleware(...middlewares);
const store = createStore(reducer, initialState, enhancer);
sagaMiddleware.run(rootSaga);
return store;
}
createIntlContext
The createIntlContext
is a helper function to create a specific context shape used by getIntl
saga. Due to limitations of the redux-saga context, this context has to be set by a user of this library in the most top saga of the application:
import { setContext, all } from 'redux-saga/effects';
import { createIntlContext } from '@ackee/jerome';
function * rootSaga() {
yield setContext(createIntlContext());
yield all([
.... sagas using getIntl()
])
}
sagaMiddleware.run(rootSaga);
Without having the context set, getIntl
saga would return null
even though the rest of the library is used properly.
getIntl(): IntlShape
The getIntl
saga returns an intl object that exactly corresponds to the intlShape
. The saga relies on proper usage of createIntlContext
Example
import { getIntl } from '@ackee/jerome';
function* mySaga() {
const intl = yield getIntl();
const translatedMessage = intl.formatMessage({
id: 'hello'
});
}
Utilities
saveLocale(locale: string)
Used for persistent store of locale setting.
Example
import { saveLocale } from '@ackee/jerome';
saveLocale('cs');
loadLocale(): string
Used for getting locale setting from persistent storage.
Example
import { loadLocale } from '@ackee/jerome';
loadLocale(); // 'cs'
localStorageHandlers
Covers both utilities mentioned above.
Example
import { localStorageHandlers } from '@ackee/jerome';
localStorageHandlers.saveLocale('en');
localStorageHandlers.loadLocale(); // 'en'