资讯专栏INFORMATION COLUMN

实战React App的i18n

arashicage / 3156人阅读

摘要:而就是产品具体实现某一种语言和文化的过程。货币的符号,以及数字分割方式各个国家都存在不同。那么有没有其他的复数形式回答当然是肯定的,比如波兰语。但这个是自己的语法,并非标准,同时这个语法还会破坏的测试,并不是一个很好的选择。

记得我刚来我们公司的时候,接手现在负责的项目的时候,我就发觉了一个问题:所有的文本资源都是硬编码在代码里面。这当然会带来很多问题。但考虑到我负责的这个项目是公司内部的管理工具,同时大部分用户都是中国人,因此抽离文本资源,做i18n的需求并不是十分强烈。

这周公司招了一位外籍员工。我并不确定她是哪一国人,不过从口音上来判断,以及言谈间她曾经提到的加利福尼亚州,我想应该是一位美国女性。老大说她会和其他的PM一样,居住在厦门,远程工作,偶尔来办公室上班。并且她也会使用我负责的这个工具。

现在i18n就有比较强烈的需求了。有必要出一个合理的架构,一劳永逸的解决问题。

i18n的主要关注点

i18n是Internationalization的缩写,实际上i18n应该是指创建或者调整产品,使得产品具有能轻松适配指定的语言和文化的能力。当然,我们还有另外一个概念,叫做Localization(简写L10n),也就是本地化。L10n正确的说是指已经全球化的产品,适配某一个具体语言和文化的这一个过程。

有点绕口,简单说就是,i18n就是给产品添加新特性,使产品能够支持对多种语言和文化(货币,时间等等)。而L10n就是产品具体实现某一种语言和文化的过程。

回过头来,i18n有这么几个主要的关注点:

Date and times formatting

Number formatting

Language sensitive string comparison

Pluralization

Date and times formatting

不同国家对应的日期格式其实都是不同的,尽管我不觉得十分复杂,不过细节的处理上也是有很多选择:

weekday,你可以设置成显示全名字,比如zh-CN的星期四,en-US的Thursday等等

month,你可以设置成数字形式,全名,短名,类似于12,December,Dec

...

完整的例子:

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time)

// US English uses month-day-year order
console.log(new Intl.DateTimeFormat("en-US").format(date));
// → "12/19/2012"

// British English uses day-month-year order
console.log(new Intl.DateTimeFormat("en-GB").format(date));
// → "19/12/2012"

// Korean uses year-month-day order
console.log(new Intl.DateTimeFormat("ko-KR").format(date));
// → "2012. 12. 19."

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.DateTimeFormat("ar-EG").format(date));
// → "١٩‏/١٢‏/٢٠١٢"

// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(new Intl.DateTimeFormat("ja-JP-u-ca-japanese").format(date));
// → "24/12/19"

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date));
// → "19/12/2012"

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// request a weekday along with a long date
var options = { weekday: "long", year: "numeric", month: "long", day: "numeric" };
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// → "Thursday, December 20, 2012, GMT"
Number formatting以及Pluralization

数字的格式化,这个比较有趣。这里说的数字,包含了货币,百分比,浮点数。其中货币的显示应该是相对比较复杂的。就以en-US来说,1000美元通常显示成$1,000.00,而1000人民币则会显示成¥1,000.00。货币的符号,以及数字分割方式各个国家都存在不同。

var number = 123456.789;

// German uses comma as decimal separator and period for thousands
console.log(new Intl.NumberFormat("de-DE").format(number));
// → 123.456,789

// India uses thousands/lakh/crore separators
console.log(new Intl.NumberFormat("en-IN").format(number));
// → 1,23,456.789

// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(new Intl.NumberFormat("zh-Hans-CN-u-nu-hanidec").format(number));
// → 一二三,四五六.七八九

var number = 123456.789;

// request a currency format
console.log(new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(number));
// → 123.456,79 €

// the Japanese yen doesn"t use a minor unit
console.log(new Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" }).format(number));
// → ¥123,457

涉及到数字的,还有另外一个问题,那就是语言的复数形式。中文似乎是没有复数形式的,比如我们经常说,一只兔子,两只兔子。但是如果你用英语,你就能明显发觉不对。在英语里,应该说one rabbit,two rabbits,many rabbits。是的,英语里主要有两种复数形式。

那么有没有其他的 复数形式?回答当然是肯定的,比如波兰语。在波兰语,兔子一词是królik,它的复数形式有这么几种情况:

兔子的数量是1,那么应该这么说,królik

如果兔子的数量在2-4之间,那么应该说,królika

如果兔子的数量不是1,并且数量在0 - 1之间,或者5 - 9之间,或者12 - 14之间,都用królików

其他情况统一用króliki

解决方案的设计 项目背景

使用facebook官方的create-react-app脚手架创建的react app

关注点

目前我的解决方案有这么几个关注点:

文本资源要能够轻易的导出

文本资源要孤立,避免和程序实现的耦合

提供极简的接口方法设计

处理语言复数形式的库,应该要能很好的拓展

技术选型

FormatJS, a modular collection of JavaScript libraries for internationalization that are focused on formatting numbers, dates, and strings for displaying to people.

解决方案 项目的目录结构
/--
  |--node_modules
  |--public
  |--src
    |--app
    |--common
    |--components
    |--configs
    |--i18n
      |--app
        |--routes
          |--setting
            |--en-US.js
            |--zh-CN.js
        |--index_en-US.js
      |--common
        |--index_en-US.js
      |--components
        |--index_en-US.js
      |--index_en-US.js
      |--index_zh-CN.js
    |--index.js
    |--logo.svg
    |--setupTests.js

如上文所示,我将所有的文本资源都独立出来,多带带存放在了i18n这个文件夹下。实际上,这些文本资源是有自己独立的命名空间的,比如/src/app相关的文本资源,就会多带带放在这个文件夹下。其他的比如/src/common//src/components/就以此类推。

Intl类

这个类很简单,封装了处理文本资源的相关方法。getText的参数key需要特别注意,这个参数应该是绝对路径,比如app.routes.setting.preferences这样。那么,相关的资源应该是要放在/src/i18n/app/routes/setting/en-US.js文件里。

class Intl {
  static COMP_COMMON_TEXT = "components.Common";
  constructor(locale, resource) {
    this.locale = locale || "zh-CN";
    this.resource = resource;
  }
  getCommonText(key, params = {}) {
    return this.getText(`${Intl.COMP_COMMON_TEXT}.${key}`, params);
  }
  getText(key, params = {}) {
    let textResource = "";
    let source = this.resource;
    const locale = this.locale;
    const properties = key.split(".");
    const hasOwnProperty = Object.prototype.hasOwnProperty;
    properties.forEach((property, index) => {
      const stillNameSpace = index !== properties.length - 1;
      if (stillNameSpace) {
        source = source[property];
      } else if (hasOwnProperty.call(source[property], "default")) {
        textResource = source[property].default;
      } else {
        textResource = source[property] || "";
      }
    });
    const msg = new IntlMessageFormat(textResource, locale);
    return msg.format(params);
  }
}
IntlProvider

这是一个React组件。这里我们要利用React提供的Context这一特性,让整个React App范围内,都会从上下文中得到getText的方法。

我们都知道,Web app初始化的时候加载的Javascript脚本是越小越好,并且我们应该尽力保证按需加载所需要的资源。这也是我们为什么利用WebPack提供的Code Splitting机制让WebPack在打包的时候,切分出多带带的chunk,减少包的体积。

在WebPack 1.x的时候,我们可以使用require.ensure()。但这个是WebPack自己的语法,并非标准,同时这个语法还会破坏Jest的测试,并不是一个很好的选择。WebPack 2.x以后就开始提供基于import()的Code Splitting机制。因此我们应该利用起来。

具体的两个文档:

WebPack的Code Splitting with ES2015

Dynamic import() proposal

class IntlProvider extends React.Component {
  static DEFAULT_LOCALE = "zh-CN";
  static propTypes = {
    locale: PropTypes.string,
    children: PropTypes.element,
  };
  static defaultProps = {
    locale: "zh-CN",
    children: null,
  };
  static childContextTypes = {
    getText: PropTypes.func,
    getCommonText: PropTypes.func,
  };
  state = {};
  constructor(props, context) {
    super(props, context);
    this.childContext = new Intl(props.locale);
  }
  async componentWillMount() {
    const { locale } = this.props;
    const lang = await import(`../i18n/index_${locale}.js`);
    this.childContext = new Intl(locale, lang);
    this.setState({
      lang,
    });
  }
  getChildContext() {
    if (!this.childContext) {
      return {
        getText: (key, params) => "",
        getCommonText: (key, params) => "",
      };
    }
    return {
      getText: (key, params) => this.childContext.getText(key, params),
      getCommonText: (key, params) => this.childContext.getCommonText(key, params),
    };
  }
  render() {
    const comp = (!this.state.lang)
    ? null
    : React.Children.only(this.props.children);
    return comp;
  }
}
App

使用的时候也是相当简单,不多说,直接上代码。

class App extends React.PureComponent {
  render() {
    const { preferences } = this.props;
    return (
      
        
{this.props.children}
); } }
参考文档

Tags for Identifying Languages

ECMAScript Internationalization API

Pluralization for JavaScript

ICU User Guide

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/89829.html

相关文章

  • 一个简单且灵活易用 React 格式化和 i18n 工具

    摘要:是一个简单且灵活易用的格式化和工具。它通过连接组件给组件一个默认为的。是一个可以根据不同的显示不同内容的函数。和内容之间的关系可以灵活地通过配置确定。在线互动演示最简单的使用方式你好欢迎你好欢迎也可与相连 react-put 是一个简单且灵活易用的格式化和 i18n 工具。 它通过连接组件给组件一个默认为 put 的 props。put 是一个可以根据不同的 key 显示不同内容的函数...

    20171112 评论0 收藏0
  • react 国际化了解一下

    摘要:先睹为快先看一下最后的成果来一发控制台中对应中的信息开始原理原理其实很简单字符串替换。拉取远程的国际化文件到本地,再根据语言做一个映射就可以了。 背景 楼主最近新接了一个项目,从0开始做,需要做多语言的国际化,今天搞了一下,基本达到了想要的效果, 在这里简单分享下: 一些探索 也说不上是探索吧,就Google了一波, GitHub 上找了一个比较成熟的库 react-i18next,...

    CrazyCodes 评论0 收藏0
  • react 国际化了解一下

    摘要:先睹为快先看一下最后的成果来一发控制台中对应中的信息开始原理原理其实很简单字符串替换。拉取远程的国际化文件到本地,再根据语言做一个映射就可以了。 背景 楼主最近新接了一个项目,从0开始做,需要做多语言的国际化,今天搞了一下,基本达到了想要的效果, 在这里简单分享下: 一些探索 也说不上是探索吧,就Google了一波, GitHub 上找了一个比较成熟的库 react-i18next,...

    魏明 评论0 收藏0
  • [ 一起学React系列 -- 10 ] i18n

    摘要:假如有这么一段句子这件衣服是人民币如果我们想将一个数字以人民币的形式写进去的话可以这么做最终显示结果是这件衣服是人民币其实它做了两件事一个是加符号,另一个是加分隔符。同时表示人民币,表示美元。 今天来介绍一个非常international的东西。 i18n国际化(internationalization)的简称。之所以叫i18n,是因为字母i和n之间有18个字母,所以才叫i18n。不...

    biaoxiaoduan 评论0 收藏0
  • React项目国际化(antd)多语言开发

    摘要:本国际化方案仅针对技术栈,且不会涉及服务端国际化内容。引入多语言环境的数据虽然我只用到了文本翻译的功能,以为就不需要加载这些数据,但后来发现这是必须的步骤。 前言 最近新接了一个项目,从0开始做,需要做多语言的国际化,今天搞了一下,基本达到了想要的效果, 在这里简单分享下: showImg(https://segmentfault.com/img/bVbuiJB); 背景国际化方案国际...

    tracymac7 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<