i18n

chenshuai2144viztormharrvicdoctorguddcat1115
Last updated on 2021-02-06 22:10:82

Getting Started

Pro implements globalization through the umi plugin @umijs/plugin-locale and is enabled by default. @umijs/plugin-locale convention Introduces the corresponding js in src/locales, such as en-US.ts and zh-CN.ts, And do the following configuration in config/config.ts:

plugins:[
   ...,
   locale: {
        enable: true,
        default: 'zh-CN',
        baseNavigator: true,
    },
    ....
]

I am happy to use the function of globalization. See config for detailed configuration)。

@umijs/plugin-locale encapsulates react-intl, api is basically the same as react-intl, and is more convenient to package. All apis are as follows:

import { setLocale, getLocale, FormattedMessage } from 'umi';

Format Message

If we have the following configuration in en-US.ts and zh-CN.ts respectively:

// zh-CN.ts

export default {
  'navbar.lang': '中文',
};

// en-US.ts

export default {
  'navbar.lang': 'English',
};

We can use this in the component

import { FormattedMessage } from 'umi';

export default () => {
  return (
    <div>
      <FormattedMessage id="navbar.lang" />
    </div>
  );
};

Set Locale

@umijs/plugin-locale exposes apis named setLocale and getLocale, which make it easy to switch between regions. The code like this:

class SelectLang extends React.Component {
  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>;
  }
}

More advanced usage can be found in plugin-locale.

Remove globalization

If you want to remove the globalization that comes with pro, you can use npm run i18n-remove, i18n-remove and compare the basics just to test the code you bring yourself. If you use advanced features, you may need to manually Go to make changes. For example, the dynamic code of formatMessage({id:somevar}) may not be able to analyze and delete it for you.

If you have a good way to achieve welcome pr.