Authors: Sky-admin, Cat not bear

background

I18n = Internationalization. Because words are made up of the first and last characters I/N and the middle 18 letters, I18n is abbreviated. For the program, it is to be able to display the corresponding interface according to different languages and regions without modifying the internal code, so as to support the smooth use of the program by people of different languages.

Business background

Internet industry enters second half, fine operation is key. Multi-language support can make the product better serve users of other languages in China, and also lay a foundation for the product to go abroad. With the globalization of WeChat/Alipay, is your small program ready?

In early April, didi Chuxing miniprogram team received a request to support the English version, which is expected to launch in early June. At present, many business lines and various public libraries integrated by Didi Chuxing’s small program need to be simultaneously connected to multiple languages, including static text with front-end hard coding displayed to users and copywriting delivered by the server. Considering the small program of the current size, light text collection, language translation, NPM package support, alignment, test, and communication cost, etc., and the front-end development in just 1.5 human cases, time is very urgent, but we withstand the pressure, finally drops travel English small program launched as scheduled, stable running until now, User feedback was good and revenue exceeded expectations.

Of course, all of this is due to the efficient work of the students and the full cooperation of the teams, and also to the elegant multi-language support of the Mpx framework of the technical team of the department. If your business needs to develop small programs and integrate them into multiple languages, then take a look at how Mpx, a small program framework, gracefully supports multiple languages. Believe that watching this article can help you know Mpx (https://github.com/didi/mpx), deepen the understanding of the framework, finally using Mpx framework efficient iterative small programs, year-end bonuses that part can play more to admire the author, to buy a cup of coffee ha (smile. JPG)

Here’s a comparison of the Chinese and English versions of Didi Chuxing’s miniapp:

You are also welcome to search didi Chuxing mini program in wechat/Alipay to experience the actual use. PS: To switch the language, open the small program, click the user’s profile picture in the upper left corner, enter the sidebar setting page, click to switch English and Chinese to experience.

Technical background

In this context, the Mpx framework — didi’s own enhanced applets framework focused on improving the development experience of applets, and the built-in I18N capability is on the agenda.

Different from WEB, the running environment of small program (this paper takes wechat small program as an example) adopts dual-thread architecture design. WebView is used to render the interface of the rendering layer, and JSCore thread is used to run JS scripts in the logic layer. Data changes at the logic layer. SetData is used to forward the data to Native (wechat client), which then forwards the data to the rendering layer to update the page. Due to the high cost of inter-thread communication, the actual project development needs to control the frequency and quantity. In addition, the rendering layer of the small program does not support running JS, and some operations such as event processing cannot be realized in the rendering layer. Therefore, wechat officially provides a set of scripting language WXS, combined with WXML, can build the structure of the page (do not know WXS? Poke here).

There are some technical difficulties and challenges in implementing I18N based on the dual-thread architecture design of applets. Due to the strong foundation built by Mpx framework in the early stage, it can finally gracefully support multi-language ability, and achieve the basic use experience consistent with VUE-I18N.

use

In terms of usage, THE API provided by THE I18N capability supported by Mpx is roughly aligned with vuE-I18N in terms of usage.

I18n is used in the template

In the compilation stage, the i18N dictionary configured by the user is combined with the translation function built in the framework and synthesized into executable WXS translation function through WXS-I18N-Loader, which is automatically injected into the template with translation function invocation. The specific invocation method is shown in the following figure.

/ / MPX file<template>
  <view>
    <view>{$t('message.hello', {MSG: 'hello'})}}</view>
    <! -- formattedDatetime computes properties that can be refreshed in response to locale changes -->
    <view>{{formattedDatetime}}</view>
  </view>
</template>
Copy the code

JS uses i18n

Through the wXS2JS capability provided by the framework, the WXS translation function into JS module is injected into the JS runtime, so that the runtime environment can also call the translation function.

/ / MPX file<script>
  import mpx, { createComponent } from '@mpxjs/core'
  createComponent({
    ready () {
      // js
      console.log(this.$t('message.hello', { msg: 'hello' }))
      // The locale change takes effect within the current component
      this.$i18n.locale = 'en-US'
      setTimeout(() = > {
        // The locale change takes effect globally
        mpx.i18n.locale = 'zh-CN'
      }, 10000)},computed: {
      formattedDatetime () {
        return this.$d(new Date(), 'long')}}})</script>
Copy the code

Define i18N dictionary

I18n configuration objects are passed in when the project is built, mainly including language dictionaries and default language types.

new MpxWebpackPlugin({
  i18n: {
    locale: 'en-US'.// Messages can be passed in either via object literals or via messagesPath specifying the path to a JS module where configurations are defined and exported. DateTimeFormats/dateTimeFormatsPath and numberFormats/numberFormatsPath similarly
    messages: {
      'en-US': {
        message: {
          hello: '{msg} world'}},'zh-CN': {
        message: {
          hello: '{MSG} the world'}}},// messagesPath: path.resolve(__dirname, '.. /src/i18n.js')}})Copy the code

If the project is generated through the CLI tool provided by Mpx, this part of the configuration will be in the mpx.conf.js file, which can be directly inline, but also specify the path of the language package.

Above, Mpx’s I18N solution has low access cost, elegant use and excellent experience. MPX i18N demo: github.com/didi/mpx/tr…

plan

The I18N support of the Mpx framework almost fully realizes the full capabilities of vuE-I18N. Let’s elaborate on the implementation of the I18N capabilities of the Mpx framework.

Plan to explore

Based on the two-thread architecture of the small program running environment, we tried different schemes, and the specific exploration process is as follows:

Scheme 1: Support I18N based on computed attributes, the data enhancement capability provided by the Mpx framework. This scheme has similar implementation ideas with UNIAPP (a comparative analysis will be made later), but it has some shortcomings, including performance overhead brought by thread communication and complicated processing in for loop scenarios, etc., so it was finally abandoned. Scheme 2: Support I18N adaptation based on WXS + JS. WXS is injected through the view layer, WXS syntax is converted into JS and then injected into the logical layer. In this way, i18N adaptation can be realized in both the view layer and the logical layer, and communication time between the two threads can be effectively reduced to some extent and performance can be improved.

Considering performance and rationality, we finally adopted scheme 2 to realize I18N scheme of Mpx.

Mpx I18N architecture design drawing

Due to the great differences in the syntax and use of WXS on various program platforms, there are also some technical difficulties in the implementation process of this scheme, which have been overcome based on the cross-platform capability built in the early stage of Mpx framework, as shown below.

Implementation difficulties

WXS runs cross-platform processing in templates

WXS is JS running in the view layer, which can reduce communication time with the logical layer and improve performance. As a result, the Mpx framework supported WXS in templates and JS runtime environments at the beginning of the iteration, and smooth-out the cross-platform WXS syntax for applets. In the template, Mpx defines a webPack Chunk template, uses wechat WXS as DSL, uses Babylon to convert the injected WXS into AST, and then traverses the AST node to smooth out the differences in WXS syntax between different platforms. Output class WXS files that can be identified by each platform. At present, it mainly supports wechat (WXS), Alipay (SJS), Baidu (Filter), QQ(QS), Toutiao (SJS) and other small program platforms.

WXS runs cross-platform processing at the logical layer

WXS is a different language from JavaScript and has its own syntax, which is not consistent with JavaScript. In addition, the operating environment of WXS is isolated from other JavaScript code, and functions defined in other JavaScript files cannot be called in WXS, nor can apis provided by applets be called. So at the logical level, Mpx converts the injected WXS syntax into JS, which is injected into the current module via Webpack. For example, the WXS global methods getRegExp/getDate cannot be called in JS. Mpx converts them into JS modules, and then injects the modules into bundle.js via webpack addVariable. Similarly, Mpx will mount compile-time injected I18N WXS translation functions and I18N configuration objects to global objects, mix them into page components with mixins, and listen on i18N configuration objects, so that JS and templates can call i18N translation functions directly to achieve data response.

These are the technical details of the Mpx framework’s ability to support I18N in applets. Since WXS is a language with jS-like syntax that can be executed at the view layer, this reduces the communication time between the applets logic layer and the view layer and improves performance. However, due to the implementation depends on class WXS capability and the limitation of WXS execution environment, currently the translation functions that can be directly used on the template include $t/$TC /$te. If you need to format numbers or dates, you can use the corresponding translation functions to achieve the calculation attribute provided by Mpx in JS.

Use i18N for web output

Mpx also supports the conversion of output H5, and the I18N capability provided by Mpx is basically the same as vuE-I18N in use. The framework will automatically introduce VUE-I18N when exporting Web, and initialize it with the current Mpx I18N configuration information. Users do not need to make any changes. You can output an I18N Web project that behaves exactly as the applet does.

contrast

The above analysis of the Mpx framework of i18N scheme technical details, we look at the comparison with other schemes, mainly with UniAPP – vUe-based writing small program scheme, and wechat official scheme, they provide i18N support and Mpx comparison of the pros and cons.

Uniapp solution

Uniapp provides support for i18N capabilities and is a direct introduction to VUE-I18N. However, JS methods cannot be invoked on templates in applets. In essence, a good language is converted using Computed attributes, and then used in applets using template interpolation.


{{message.hello}}

JS needs to write:

  computed: {  
    message () {  
      return { hello: this.$t('message.hello')}}}Copy the code

Therefore, this scheme has a performance problem. The text seen by the final rendering layer is still completed through setData cross-thread communication, which will lead to increased inter-thread communication and high performance overhead.

In addition, the early use of this form is high cost, and later UniApp has also made optimization for it, realizing the ability to write $t() on the template, using the upper part of a lot of convenience.

This implementation of t() that recognizes t() at compile time and automatically replaces it when it recognizes t at compile time, helps you replace it with a computed data of UNIApp, so the data part has to be maintained in two copies as before. In particular, the for loop on the template, even if only one data in the FOR is converted, replaces the entire list with a calculated property, further increasing the performance overhead when communicating between threads.

Wechat official program

Wechat miniprogram itself also provides an i18n program, the repository address is: wechat-miniprogram/miniprogram-i18n.

This solution is similar to the DESIGN of the Mpx framework in terms of the implementation of i18N itself, and is also based on WXS implementation (great minds think alike). However, because there is no complete system surrounding the supporting system, the overall use experience is also slightly inferior to the DEVELOPMENT of international small programs based on Mpx framework to support I18N.

The main point is that the scheme provided by the authorities requires an additional build based on gulp tool, and an additional behavior should be introduced when used in JS so that translation capability can be used in JS.

While Mpx framework through a unified Webpack build output complete content, users do not need to worry about language pack update forget to rebuild, when used in JS not only more convenient, and language information is responsive, any component can easily listen to the change of language value to do some other things.

Finally, Mpx’s i18N program has a huge advantage over wechat’s official program. Combined with Mpx’s cross-platform capability, it can realize the implementation of this program, a set of code output to support wechat/Alipay/Baidu /QQ/ Toutiao platforms supporting I18N small programs.

conclusion

Mpx framework focus on small program development, expect to provide developers with the most comfortable development experience, there are many excellent features to help developers improve efficiency. This paper introduces its built-in I18N capability. Through comparative analysis, it is concluded that it has obvious advantages in terms of cost and performance compared with other framework solutions. Students with relevant requirements are welcome to try it.

In the future, Mpx will continue to iterate, providing more and better capabilities to help small program developers improve performance. If you have any problem with Git, you are welcome to raise an issue on Git, and team members will respond promptly. We also encourage you to contribute to the open source community, participate in Mpx, and contribute to the development of applets technology.

GitHub address github.com/didi/mpx Mpx document mpxjs.cn/

Welcome technical exchange and feedback, by the way star encourage open source project contributors, we will continue to contribute to the community.

The attached: Past Mpx article link small drops open source application framework Mpx – https://mpxjs.cn/articles/1.0.html drops small application framework Mpx release 2.0, support small cross-platform development program, Can be directly convert existing WeChat small program – https://mpxjs.cn/articles/2.0.html small developers, Why you should try the MPX – https://mpxjs.cn/articles/mpx1.html MPX applet framework technology reveal – https://mpxjs.cn/articles/mpx2.html drops travel small program optimization practice – volume https://mpxjs.cn/articles/size-control.html