The author:
sky-admin,
When the cat’s not bear

background

I18n = Internationalization, because words consist of the first and last characters I /n and the middle 18 letters, or I18n for short. For the program, is to do not modify the internal code, according to different languages and regions to display the corresponding interface, in order to support people in different languages smoothly use the program.

Business background

Internet industry into the second half, fine operation is the key. Multilingual support allows the product to better serve users in other languages within the territory, and also lays a foundation for the product to go abroad. With the globalization of WeChat/ AliPay, is your small program ready?

In early April, the Didi Chuxing mini program team received a demand to support the English version, which is expected to be launched in early June. At present, the numerous business lines and various public libraries integrated by Didi Chuxing applets, such as hardcoded static text at the front end and copywriting issued by the server end, must be synchronously connected to multiple languages. 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, The user feedback was good and the revenue exceeded expectations.

Of course, all of this is due to the efficient work of all the team members, and the full cooperation of all the teams, but also due to the department’s technical team MPX framework elegant multi-language ability support. If you’re in the business of developing small programs and having access to multiple languages, then take a look at how the small program framework MPX elegantly supports multilingual capabilities. 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)

Below is a comparison of the Chinese and English versions of Didi Chuxing mini-program:

Welcome to WeChat/Alipay search Didi Chuxing small program, the actual use of the experience. PS: The way to switch languages is to open the small program, click the user’s portrait in the upper left corner, enter the sidebar setting page, and click “Switch English and Chinese” to experience.

Technical background

Under the above business background, the MPX framework, an enhanced small program framework developed by Didi, which focuses on improving the small program development experience, has been put on the agenda with the built-in i18n capability.

Different from Web, the running environment of small programs (this paper takes WeChat small programs as an example) adopts double-threaded architecture design. The interface of rendering layer uses WebView to render, and the logic layer uses JSCORE thread to run JS scripts. The data of logical layer is changed, and the data is forwarded to Native (WeChat client) through setData, which then forwards the data to 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 small program rendering layer does not support running JS, some operations such as event processing can not be implemented in the rendering layer, so WeChat official provides a set of scripting language WXS, combined with WXML, you can build the structure of the page (do not know WXS? Poke here).

Based on the dual-thread architecture design of small programs, there are some technical difficulties and challenges to realize i18n. Due to the strong foundation of the MPX framework built early, it can finally elegently support multi-language ability, and achieve the basic consistent use experience with Vue-i18n.

use

In terms of usage, the API provided by the MPX support i18n capability is roughly aligned with that of Vue-i18n, and is generally consistent in usage.

I18n is used in the template

In the compilation stage, the user-configured i18n dictionary, combined with the translation function built in the framework, is synthesized into an executable WXS translation function through WXS-i18n-Loader, and automatically injected into the template with translation function call. The specific invocation method is shown in the figure below.

/ / MPX file < template > < view > < view > {{$t (' message. Hello, {MSG: 'hello'})}} < / view > <! --> <view>{{formattedDatetime}}</view> </view> </template> --> <view>{{formattedDatetime}

I18n is used in JS

Through the framework’s WXS2JS capabilities, the WXS translation function is transformed into a JS module and injected into the JS runtime, so that the runtime environment can also call the translation function.

// MPX <script> import MPX, {createComponent} from '@mpxjs/core' createComponent({ready () {// js use console.log(this.$t('message.hello'), { msg: $i18n. Locale = 'EN-US' setTimeout(() => {// This.$i18n. MPX.i18n.locale = 'zh-cn'}, 10000)}, computed: { formattedDatetime () { return this.$d(new Date(), 'long') } } }) </script>

Define the i18n dictionary

The i18n configuration object is passed in when the project is built, which consists mainly of the language dictionary and the default language type.

new MpxWebpackPlugin({ i18n: { locale: 'en-us ', // Messages can be either passed in as object literals or specified as a JS module path via MessagesPath where the configuration is defined and exported. DateTimeFormats/dateTimeFormatsPath and numberFormats/numberFormatsPath similarly messages: {' en - US: {message: {hello: 'world' {MSG}}}, 'useful - CN: {message: {hello:' {MSG} world '}}}, / / messagesPath: path. Resolve (__dirname, '.. /src/i18n.js') } })

If the project is generated through the CLI tools provided by MPX, this part of the configuration will be in the mpx.conf.js file, and you can not only write it inline directly to the file, but also specify the path to the language package.

Above, MPX’s i18n solution has low access cost, elegant use and excellent experience. Intuitive feelings may refer to the following MPX i18n demo: https://github.com/didi/mpx/t…

plan

The MPX framework’s i18n support almost completely implements the full capabilities of Vue-i18n. Let’s detail the implementation of the MPX framework’s i18n capabilities.

Plan to explore

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

Scenario 1: Support i18n with enhanced Computed Computation attributes based on the data already provided by the MPX framework. This scheme is similar to the implementation idea of UniApp (which will be compared and analyzed later), but it has some shortcomings, including the performance overhead brought by thread communication and the complexity of processing in the scenario of for loop, etc., so it is finally abandoned. Scheme 2: I18N adaptation is supported based on WXS + JS. WXS is injected through the view layer, and the WXS syntax is converted into JS and injected into the logical layer. In this way, both the view layer and the logical layer can realize i18N adaptation, and effectively reduce the communication time between the two threads to a certain extent and improve the performance.

Considering the performance and rationality, we finally adopted the second scheme to implement MPX’s i18n scheme.

MPX i18n architecture design

Due to the large differences in syntax and usage of WXS on different large and small programming platforms, there are also some technical difficulties in the implementation process of this scheme. These difficulties have been overcome based on the cross-platform capabilities built in the early stage of MPX framework. The details are as follows.

Implementation difficulties

Cross-platform processing that WXS runs in templates

WXS is JS running in the view layer, which can reduce communication time with the logical layer and improve performance. Therefore, the MPX framework has already supported the use of WXS language in templates and JS runtimes at the beginning of the iteration, and smooths out the cross-platform WXS syntax for small programs. In the template, MPX customizes a Webpack Chunk Template with WeChat WXS as the DSL, converts the injected WXS into AST with Babylon, and then traverse the AST nodes to erase the differences in the processing of WXS syntax by the major platforms. Output WXS-like files that are recognized by each platform. At present, it mainly supports WeChat (WXS), Alipay (SJS), Baidu (Filter), QQ(QS), Toutiao (SJS) and other small program platforms.

Cross-platform processing that WXS runs at the logical layer

WXS is a different language from JavaScript and has its own syntax, which is not consistent with JavaScript. Moreover, WXS’s runtime environment is isolated from other JavaScript code. 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 and injects it into the current module via Webpack. For example, the WXS global methods getRegexp /getDate are not available in JS. MPX converts them into JS modules separately and injects them into Bundle.js via Webpack AddVariable. In the same way, MPX will mount the i18n WXS translation function and the i18n configuration object injected at compile time to the global object, mix it into the page component with mixins, and listen on the i18n configuration object, so that JS and template can call the i18n translation function directly to implement the data response.

These are the technical details of how the MPX framework supports i18n capabilities in applets. Since WXS is a language with JS-like syntax that can be executed in the view layer, this reduces the communication time between the applet logic layer and the view layer and improves performance. However, due to the implementation of dependent class WXS ability, as well as the WXS execution environment restrictions, currently can be directly used on the template translation functions include $t/$tc/$te, if you need to format the number or date can use the corresponding translation function in JS MPX provided by the calculation properties to achieve.

I18n is used 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 usage. When output web, the framework will automatically introduce Vue-i18n and initialize it with the current MPX i18n configuration information, without any changes to the user. You can output i18n Web projects that behave exactly the same as small programs.

contrast

The above analysis of the MPX framework i18n solution technical details, we look at the comparison with other solutions, mainly and Uniapp – based on Vue to write small programs, and WeChat official solution, the two provide i18n support and MPX comparison is good and bad.

Uniapp solution

Uniapp provides support for i18n capabilities and is a direct introduction to Vue-i18n. However, there is no way to call a JS method on a template in a small program. Instead, we use a Computed attribute, Computed, to transform the language, and then use template interpolation to use it in a small program template.


{{message.hello}}

JS need to write:

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

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

In the early days, this form was expensive to use, but Uniapp optimized it and realized the ability to write $t() on the template, which made it much easier to use.

The $t() implementation automatically replaces $t when it is recognized at compile time, and replaces you with a computed uniapp data, so the data portion is still maintained in two copies as before. In particular, for loops on templates, where even if only one data in the for is to be converted, the entire list is replaced with a single computed property, further increasing the performance overhead when communicating between threads.

WeChat official program

WeChat applet itself also provides an i18n solution, the warehouse address is: wechat-miniprogram/miniprogram-i18n.

This solution is similar to the design of the MPX framework in terms of the i18n implementation itself, and is also based on WXS implementation (great minds think alike). But because there is no complete system around the supporting system, the overall use experience is slightly inferior to the development of i18n based on the MPX framework to support the internationalization of small programs.

The main point is that the official solution requires an extra build based on the gulp tool, and an extra behavior to be introduced when it is used in JS to enable translation in JS.

The MPX framework produces complete content through a unified Webpack build, so users don’t have to worry about forgetting to rebuild the language package after updating. It is not only more convenient to use in JS, but also the language information is responsive, so any component can easily listen for the change of the language value to do other things.

Finally, MPX i18N scheme compared with WeChat official scheme has a huge advantage, combined with the cross-platform ability of MPX, can achieve all with this scheme, a set of code output support WeChat/Alipay/Baidu /QQ/ Toutiao platform support i18N small program.

conclusion

MPX framework focus on small program development, expected to provide developers with the most comfortable development experience, there are many excellent features to help developers to improve the effect. 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. Welcome all students with relevant requirements to try it out.

In the future, MPX will continue to iterate and improve to provide more and better capabilities to help small program developers. If you encounter any problem in the process of using it, you are welcome to issue it on Git, and the team members will respond in time. We also encourage you to contribute to the open source community, participate in the building of MPX, and contribute to the development of small program technology.

Git address [https://github.com/didi/mpx] Mpx document [https://mpxjs.cn/]

Technical exchanges and feedback are welcome. By the way, STAR encourages contributors to open source projects. 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