---
order: 13
title: 國際化
type: 進階
---
### 開始使用
pro 通過 umi 插件 [umi-plugin-locale](https://github.com/umijs/umi-plugin-locale) 來實現全球化的功能,并且默認開啟。 `umi-plugin-locale` 約定 在 src/locales 中引入 相應的 js,例如 en-US.ts 和 zh-CN.ts,并且在 `config/config.ts` 中做如下配置:
```js
plugins:[
...,
locale: {
enable: true,
default: 'zh-CN',
baseNavigator: true,
},
....
]
```
就可以在代碼中使用全球化的功能了。詳細配置參見[config](https://github.com/umijs/umi-plugin-locale#usage)。
`umi-plugin-locale` 封裝了[react-intl](https://github.com/yahoo/react-intl), api 與 `react-intl` 基本相同,并做了封裝使用起來更加方便。全部 api 如下:
```js
import { formatMessage, setLocale, getLocale, FormattedMessage } from 'umi/locale';
```
### 格式化字符串
如果我們在 `en-US.ts` 和 `zh-CN.ts` 中分別作了如下配置:
```js
// en-US.ts
export default {
'navbar.lang': '中文',
}
// zh-CN.ts
export default {
'navbar.lang': 'English',
}
```
我們就可以在組件中這樣使用
```js
import { FormattedMessage } from 'umi/locale';
export default () => {
return (
<div>
<FormattedMessage id="navbar.lang" />
</div>
);
};
```
在某些情況下,你可能需要直接返回 string。你可以這樣使用:
```js
import { formatMessage } from 'umi/locale';
export default () => {
return <div>{formatMessage({ id: 'navbar.lang' })}</div>;
};
```
### 設置區域
`umi-plugin-locale` 暴露了名為 `setLocale` 和 `getLocale` 的 api,通過這兩個 api 可以方便的切換區域。代碼看起來像這樣的:
```js
...
changLang = () => {
const locale = getLocale();
if (!locale || locale === 'zh-CN') {
setLocale('en-US');
} else {
setLocale('zh-CN');
}
};
render(){
<Button
size="small"
ghost={theme === 'dark'}
style={{
margin: '0 8px',
}}
onClick={() => {
this.changLang();
}}
>
<FormattedMessage id="navbar.lang" />
</Button>
}
```
更多高級的用法可以參照 [react-intl 的 api](https://github.com/yahoo/react-intl/wiki#getting-started)。
### 刪除全球化
如果你想刪除 pro 自帶的全球化,可以通過 `npm run i18n-remove`,`i18n-remove`還比較基礎只是測試了 pro 自帶的代碼,如果你使用了高級的特性,你可能需要自己人工去進行修改。例如 `formatMessage({id:somevar})` 這種動態的代碼我們可能無法幫您分析并刪除。
如果你有好辦法可以實現 歡迎 [pr](https://github.com/ant-design/ant-design-pro-cli)。