书接前文,继续分享即便在项目中import Singleton后,但因为种种不规范、不推荐的写法和配置,引发的国际化问题。
问题分析
本案依然是一个字符串读取问题,现象如下:
在产品的中文主页面上的点击导航栏,发现少量模块(如图中所示的Subscription)的内容回退为英文,而在之前的若干轮测试中,该模块已经可以完美的展示中文内容。代码短期内未发生修改,确认对应的string已经被本地化,不存在遗漏或误删除问题。
不卖关子啦,因为本例的背景着实非常小众和特殊,不便引发大家的种种推测,这里直接公布答案——本项目中很早就引入了Singleton作为i18n框架,而在随后的岁月中,Singleton本身经过了几次重要的升级,导致老版本和新版本在string loading的处理上有着两套截然不同的逻辑体系。老版本(6.4.10之前)使用了scanner来收集source string,而之后的版本(最新版为13.0.0)中为了避免代码中出现hardcode source string对translate pipe进行了大规模升级。好巧不巧,本项目中正是因为不同模块在load string的过程中因为使用的Singleton版本不同,同时又没有严格按照Singleton框架所要求的步骤进行操作,从而导致了该问题的发生。
解决方案
首先,我们需要在HTML模板文件中对负责string loading的pipe进行替换,修改老版本中的translate为vtranslate。
// Old version
<clr-alert-item>
<span class="alert-text">
{{ 'create-subscription-payment-body.order-issue' | translate: 'Uh oh. We\'ve encountered an issue placing this order {0}.' : errorMessage }}
{{ 'create-subscription-payment-body.please-contact-csm' | translate: 'Please contact your Customer Success Manager at 877-486-9273 for assistance.' }}
</span>
</clr-alert-item>
// Now
<clr-alert-item>
<span class="alert-text">
{{ 'create-subscription-payment-body.order-issue' | vtranslate: errorMessage }}
{{ 'create-subscription-payment-body.please-contact-csm' | vtranslate }}
</span>
</clr-alert-item>
其次,在对应的component.ts文件中修改原先的this.l10n.translate方法为this.l10.getMessage。
// Old version
public readonly nextBtnText = this.l10n.translate('create-subscription.next', 'Next');
public readonly pageTitle = this.l10n.translate('create-subscription.page-title', 'Create Subscription');
…
// Now
public readonly nextBtnText = this.l10n.getMessage('create-subscription.next');
public readonly pageTitle = this.l10n.getMessage('create-subscription.page-title');
…
再次刷新对应模块,发现localized string无法load的问题不再存在。
总结
目前Singleton框架关于string loading提供了两种不同的方式,所以一旦您的项目中存在老版本(6.4.10之前)的Singleton框架及对应的translate pipe调用,又不想进行宏替换为新版本API时,请务必遵循推荐的标准流程,先用scanner进行扫描。当然,笔者推荐的解决方案还是统一使用最新版(13.0.0)的Singleton vtranslate pipe(主动发送模式)对项目的国际化进行支持。否则在同一产品内则需要维护两套国际化用法和规则,这势必会让开发人员混淆,甚至忘记二者详细的操作步骤,类似于本案的怪现象仍会“层出不穷”。另外,日后一旦发生代码重构,scanner的路径也会相应的发生变化,这又将是新bug的温床。