Home  >  Article  >  WeChat Applet  >  Mini Program I18n Best Practice Cases

Mini Program I18n Best Practice Cases

coldplay.xixi
coldplay.xixiforward
2020-09-07 13:25:223666browse

Mini Program I18n Best Practice Cases

Related learning recommendations: WeChat Mini Program Tutorial

Background

I18n = Internationalization, internationalization, because the word consists of the first and last characters i/n and the middle 18 letters, it is referred to as i18n. For the program, it is necessary to display the corresponding interface according to different languages ​​​​and regions without modifying the internal code, so as to support people with different languages ​​​​to use the program smoothly.

Business Background

The Internet industry has entered the second half, and refined operations are the key. Multi-language support allows the product to better serve users of other languages ​​in the country, and also lays the foundation for the product to go overseas. With the globalization of WeChat/Alipay, are your mini programs ready?

In early April, the Didi Travel Mini Program team received a request to support the English version, and it is expected to be launched in early June. Currently, Didi’s travel mini-program integrates many business lines and various public libraries. The front-end hard-coded static text and the copy issued by the server that are displayed to users must be simultaneously accessed in multiple languages. Considering the current size of the mini program, text collection, corpus translation, npm package support, joint debugging, testing, communication costs, etc., and only 1.5 manpower is invested in front-end development, time is quite tight, but we resist After overcoming the pressure, the English version of the Didi Travel mini program was finally launched as scheduled. So far, it is running stably, with good user feedback, and has received benefits beyond expectations.

Of course, all this is due to the efficient work of the students in each team, the full cooperation of each team, and also the elegant multi-language support of the Mpx framework of the department’s technical team. Let’s focus on this. It is said that if you want to do your job well, you must first sharpen your tools. If your company’s business needs to develop small programs and also need access to multiple languages, then please move the small bench and let’s take a look at the small program framework Mpx. How to elegantly support multi-language capabilities. I believe that after reading this article, it can help you get to know Mpx (https://github.com/didi/mpx), deepen your understanding of the framework, and finally use the Mpx framework to efficiently iterate small programs. You can reward the extra part of the year-end bonus. Author, buy a cup of coffee (smirk.jpg)

The following is a comparison of the Chinese and English versions of the Didi Chuxing applet:

Mini Program I18n Best Practice Cases

You are also welcome to search for Didi Travel Mini Program on WeChat/Alipay and experience the actual use. PS: To switch the language, open the mini program, click on the user avatar in the upper left corner, enter the sidebar settings page, and click to switch between Chinese and English to experience it.

Technical background

Under the above business background, the Mpx framework - an enhanced mini program framework independently developed by Didi that focuses on improving the mini program development experience, with built-in i18n capabilities is on the agenda. .

Different from the WEB, the running environment of mini programs (this article takes WeChat mini programs as an example) is designed with a dual-thread architecture. The interface of the rendering layer uses WebView for rendering, and the logic layer uses JSCore threads to run JS scripts. When the logic layer data changes, the data is forwarded to Native (WeChat client) through setData, and Native then forwards the data to the rendering layer to update the page. Due to the high cost of communication between threads, the frequency and quantity need to be controlled during actual project development. In addition, the rendering layer of the mini program does not support running JS, and some operations such as event processing cannot be implemented in the rendering layer. Therefore, WeChat officially provides a set of scripting language WXS. Combined with WXML, the structure of the page can be constructed (don’t know WXS? Click here ).

Based on the dual-thread architecture design of small programs, there are some technical difficulties and challenges in implementing i18n. Due to the strong foundation built in the early days of the Mpx framework, it was finally able to elegantly support multi-language capabilities and implement vue-i18n Basically the same experience.

Usage

In terms of use, the API provided by Mpx's support for i18n capabilities is generally aligned with vue-i18n, and the usage is basically the same.

i18n is used in the template

In the compilation phase, the i18n dictionary configured by the user is combined with the built-in translation function of the framework to be synthesized into an executable WXS translation function through wxs-i18n-loader, and is automatically injected Go to the template with translation function call, the specific calling method is as follows.

// mpx文件复制代码

I18n

is used in JS through the wxs2js capability provided by the framework to convert the WXS translation function into a JS module and inject it into the JS runtime, so that the translation function can also be called in the runtime environment.

// mpx文件复制代码

Definition of i18n dictionary

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

new MpxWebpackPlugin({  i18n: {    locale: 'en-US',    // messages既可以通过对象字面量传入,也可以通过messagesPath指定一个js模块路径,在该模块中定义配置并导出,dateTimeFormats/dateTimeFormatsPath和numberFormats/numberFormatsPath同理
    messages: {      'en-US': {        message: {          hello: '{msg} world'
        }
      },      'zh-CN': {        message: {          hello: '{msg} 世界'
        }
      }
    },    // messagesPath: path.resolve(__dirname, '../src/i18n.js')
  }
})复制代码

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. Not only can it be written directly inline in the file, but the path to the language pack can also be specified. .

Above, Mpx’s i18n solution has low access cost, elegant use and excellent experience. For intuitive feelings, please refer to the mpx i18n demo below: github.com/didi/mpx/tr…

方案

Mpx框架的 i18n 支持几乎完全实现了 vue-i18n 的全部能力,下面我们来详细说明 Mpx 框架 i18n 能力的具体实现。

方案探索

基于小程序运行环境的双线程架构,我们尝试了不同方案,具体探索过程如下:

方案一:基于 Mpx 框架已提供的数据增强能力 computed 计算属性,来支持 i18n 。该方案与 uniapp 的实现思路相似(后文会进行对比分析),存在一定不足,包括线程通信带来的性能开销和for循环场景下的处理较复杂等,最终放弃。
方案二:基于 WXS + JS 支持 i18n 适配。通过视图层注入 WXS,将 WXS 语法转换为 JS 后注入到逻辑层,这样视图层和逻辑层均可实现 i18n 适配,并且在一定程度上有效减少两个线程间的通信耗时,提高性能。

从性能和合理性上考虑,我们最终采用了方案二进行 Mpx 的 i18n 方案实现。

Mini Program I18n Best Practice Cases

Mpx i18n 架构设计图

由于各大小程序平台上,WXS 语法和使用均存在较大差异,因此该方案实现过程中也存在一些技术上的难点,这些难点基于 Mpx 框架的早期构建起来的跨平台能力也一一得以攻克,具体如下。

实现难点

WXS 在模板中运行的跨平台处理

WXS 是运行在视图层中的 JS,可以减少与逻辑层通信耗时,提高性能。因此 Mpx 框架在迭代初期便已支持在模板和 JS 运行环境使用 WXS 语言,并且针对小程序跨平台 WXS 语法进行抹平。 在模板中,Mpx 自定义一个 webpack chunk template,以微信 WXS 作为 DSL,利用 babylon 将注入的 WXS 转化成 ast,然后遍历 ast 节点,抹平各大平台对 WXS 语法的处理差异,输出各平台可以识别的类 WXS 文件。目前主要支持微信(WXS)、支付宝(sjs)、百度(filter)、QQ(qs)、头条(sjs)等小程序平台。

WXS 在逻辑层运行的跨平台处理

WXS 与 JavaScript 是不同的语言,有自己的语法,并不和 JavaScript 一致。并且 WXS 的运行环境和其他 JavaScript 代码是隔离的,WXS 中不能调用其他 JavaScript 文件中定义的函数,也不能调用小程序提供的API。 因此在逻辑层,Mpx 将注入的 WXS 语法转化为 JS,通过 webpack 注入到当前模块。例如 WXS 全局方法 getRegExp/getDate 在 JS 中是无法调用的,Mpx将它们分别转化成 JS 模块,再通过 webpack addVariable 将模块注入到 bundle.js 中。 同理,Mpx 会将编译时注入的 i18n wxs 翻译函数和 i18n 配置对象挂载到全局 global 对象上,利用 mixin 混入到页面组件,并监听 i18n 配置对象,这样JS和模板中即可直接调用 i18n 翻译函数,实现数据响应。

以上便是 Mpx 框架在小程序中支持 i18n 能力的技术细节,由于 WXS 是可以在视图层执行的类 JS 语法的一门语言,这样就减少了小程序逻辑层和视图层的通信耗时,提升性能。但是由于实现依赖类 WXS 能力,以及 WXS 执行环境的限制,目前模板上可直接使用的翻译函数包括 $t/$tc/$te ,如果需要格式化数字或日期可以使用对应的翻译函数在 JS 中 Mpx 提供的计算属性中实现。

输出 web 时使用 i18n

Mpx同时还支持转换产出H5,而 Mpx 提供的 i18n 能力在使用上与 vue-i18n 基本一致,输出 web 时框架会自动引入 vue-i18n,并使用当前的 Mpx i18n 配置信息对其进行初始化,用户无需进行任何更改,即可输出和小程序表现完全一致的 i18n web 项目。

对比

上面分析了 Mpx 框架的 i18n 方案的技术细节,我们来看下和其他方案的对比,主要是和 uniapp - 基于 Vue 编写小程序的方案,和微信官方的方案,两者提供的 i18n 支持与Mpx的对比有何优劣。

uniapp的方案

uniapp 提供了对 i18n 能力的支持,是直接引入vue-i18n。但小程序中无法在模板上调用 JS 方法,本质上是利用计算属性 Computed 转换好语言,然后利用模板插值在小程序模板中使用。

模板中:{{ message.hello }}

JS里需要写:

  computed: {  
    message () {  
      return { hello: this.$t('message.hello') }
    }
  }复制代码

因此该方案存在一个性能问题,最终的渲染层所看到的文本还是通过 setData 跨线程通信完成,这样就会导致线程间通信增多,性能开销较大。

Furthermore, in the early days, this form was more expensive to use. Later, uniapp also optimized it and realized the ability to write $t() on the template, which made it much more convenient to use.

The implementation of $t() is to automatically replace $t when it is recognized during compilation, and replace it with a uniapp computed data for you, so the data part still needs to be maintained in two copies as before. Especially the for loop on the template, even if only one data in for needs to be converted, the entire list must be replaced with a calculated attribute, which further increases the performance overhead when communicating between threads.

WeChat’s official solution

The WeChat mini program 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 implementation of i18n itself, and is also based on WXS implementation (the hero sees the same thing). However, because there is no complete system for peripheral support, the overall user experience is slightly inferior to developing international applets that support i18n based on the Mpx framework.

The main point is that the official solution requires an additional build based on the gulp tool, and when used in JS, an additional behavior must be introduced to allow translation capabilities to be used in JS.

The Mpx framework produces complete content through a unified Webpack build. Users do not need to worry about forgetting to rebuild after the language pack is updated. Not only is it more convenient to use it in JS, but the language information is also responsive. , any component can easily listen to changes in language values ​​and do other things.

Finally, Mpx’s i18n solution has a huge advantage over WeChat’s official solution. Combined with Mpx’s cross-platform capabilities, it can be achieved with this solution. A set of code output supports WeChat/Alipay/Baidu/ QQ/Toutiao multiple platforms support i18n applet.

Summary

The Mpx framework focuses on small program development and hopes to provide developers with the most comfortable development experience. It has many excellent functional features to help developers improve efficiency. This article introduces its built-in i18n capabilities. Through comparative analysis, it is concluded that it has obvious advantages in terms of cost and performance compared to other framework solutions. Students with relevant needs are welcome to try it out.

If you want to know more about programming learning, please pay attention to the php training column!

The above is the detailed content of Mini Program I18n Best Practice Cases. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete