实战React App的i18n
记得我刚来我们公司的时候,接手现在负责的项目的时候,我就发觉了一个问题:所有的文本资源都是硬编码在代码里面。这当然会带来很多问题。但考虑到我负责的这个项目是公司内部的管理工具,同时大部分用户都是中国人,因此抽离文本资源,做i18n的需求并不是十分强烈。 这周公司招了一位外籍员工。我并不确定她是哪一国人,不过从口音上来判断,以及言谈间她曾经提到的加利福尼亚州,我想应该是一位美国女性。老大说她会和其他的PM一样,居住在厦门,远程工作,偶尔来办公室上班。并且她也会使用我负责的这个工具。 现在i18n就有比较强烈的需求了。有必要出一个合理的架构,一劳永逸的解决问题。 i18n的主要关注点i18n是Internationalization的缩写,实际上i18n应该是指创建或者调整产品,使得产品具有能轻松适配指定的语言和文化的能力。当然,我们还有另外一个概念,叫做Localization(简写L10n),也就是本地化。L10n正确的说是指已经全球化的产品,适配某一个具体语言和文化的这一个过程。 有点绕口,简单说就是,i18n就是给产品添加新特性,使产品能够支持对多种语言和文化(货币,时间等等)。而L10n就是产品具体实现某一种语言和文化的过程。 回过头来,i18n有这么几个主要的关注点:
Date and times formatting不同国家对应的日期格式其实都是不同的,尽管我不觉得十分复杂,不过细节的处理上也是有很多选择:
... 完整的例子: var date = new Date(Date.UTC(2012,11,20,3,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,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美元通常显示成 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 |