Home Page
Column
Online Course
Developer Tools
Home Page
Column
Online Course
Developer Tools
更多
Follow the community
User Center
Developer Center
>
Column
>
Details
Introduction to Cross-End Development of Taro applet
Self-justification Tech
2021-05-11
IP归属:未知
76100 browse
Computer Programming
Front-end
## Background At the beginning, we only worked on WeChat mini programs. With the expansion of our business and the rise of various application platforms, it is not realistic to write different sets of code for different platforms. Moreover, the native mini program development model has many drawbacks. In order to make the development of Mini Program easier and more efficient, we select Taro as our preferred frame and provide our practical experience on Taro, with focus on “what is Taro”, “why do we use Taro” and “how to use Taro” (right gesture), as well as some design ideas behind Taro, so that everyone can have a complete understanding of Taro. Since the technology of Taro 3.0 has gradually matured, and our project has been upgraded to Taro 3.0, the code examples in this article are based on Taro 3.0. ## What is Taro Taro is a multi-terminal, unified development framework. Taro supports React development. Writing code that can run multiple terminals once can generate multi-terminal applications, such as mini programs, H5, and even React Native. Official introduction to Taro: Taro is an open cross-terminal cross-framework solution that supports the development of WeChat, JD, Baidu, Alipay, Bytedance, QQ mini program, H5, React Native and other applications using frameworks such as React/Vue/Nerv. Terminals come in a variety of forms, such as Web, React Native, and WeChat Mini Program. It would be extremely expensive to write multiple sets of code for different terminals when the performance on different terminals is required by the business at the same time. In this case, the ability to write a single set of code that can be compatible with multiple applications is in great demand. Its main features are: Quick: Mini programs can be developed quickly: Solve various pain points of mini program development; Multiple: Multi-terminal adaptation can be realized: A set of code can adapt to small program, H5, RN and other terminals; ## Why do we use Taro As applications grow larger and more complex, the pain points of native mini program development are gradually exposed: • Complex code organization: The file structure in writing a page is cumbersome (up to four) • Inconsistent conventions: Different naming conventions for components and methods, different writing styles, and different syntax structures that resemble both React and Vue • Weak string template: Not very logical and do not support ESLint • Disorganized dependency management: Lack of NPM package dependency management • Incomplete ES Next: Only part of ES Next syntax is supported. Newer ES2020 and ES2021+ are not supported • Backward development methods: The front-end engineering system is imperfect, webpack packaging, css preprocessing, etc. are missing, which are relatively backward for the front-end and are not good for personal development. #### Options The industry provides the following options to solve the above pain points of the WeChat mini program development model:  <center></center> #### Comparison analysis  - mpvue, a framework developed by Meituan, features poor multi-terminal adaptation and poor maintenance; - WePY, a componentized framework from Tencent, cannot adapt to multiple terminals; - Chameleon has outstanding performance in multi-terminal adaptation. Its disadvantage is that it does not support JD mini programs and cannot convert native mini programs (if you want to use it, you can only rewrite the project); - Taro has excellent features, it follows the React/Vue syntax rules, and introduces a modern development process, allowing the development to focus more on core code and providing a sound code inspection method. #### Multi-terminal demands  Taro supports the most platforms. It has unique conversion capabilities, and outperforms other frameworks. Its features can be summarized as follows: - It can convert the native code of WeChat mini program to WeChat platform, Baidu platform, etc.; - Taro framework is the only framework that can adapt to JD mini programs; - It supports React/Vue syntax, with better support for componentization and TypeScript; - It features great industry influence, active community. As a framework developed by the competent JD technical team, it is technically guaranteed; - A more complete UI component base, supporting multi-terminal synchronous debugging and adapting to more terminals; **Writing once, running on multiple terminals**  ## Design ideas #### Mainly using React development method  #### Writing multi-terminal applications with React  #### Core ideas Code conversion: Enable code to run on different platforms Runtime adaptation: Make code have the same performance on different platforms #### Take WeChat Mini Program as an example  JSX  WXML  #### Compilation principle of Taro code  Compilation principle of Taro: It is the process of parsing the input source code, constructing the syntax tree, transforming the syntax tree and then parsing and generating the target code. Specifically, it first parses the code into an Abstract Syntex Tree (AST), and then traverses and replaces the AST (which is not new to the front end and can be analogous to DOM Tree operations), and finally generates compiled code based on the new AST. During the development, the React syntax standard is followed, and a series of conversion operations are performed on the code file in combination with the idea of compilation principle. Finally, the code that can run in the mini program is obtained. React was originally designed for Web development, so the code that can run on the Web can be generated directly with a few modifications. This also facilitates the support from React Native, which also belongs to the React syntax system. Similarly for other platforms, such as rapid application and Baidu mini program, the corresponding syntax code under the platform can also be obtained by compiling and converting the source code.     It can be seen that the component standards on the mini programs and the web are quite different from the API standards. These differences cannot be eliminated only by means of code compilation. For example, you cannot directly compile the <view/> of the mini program into <div/>, although they look similar, their component attributes are very different, and they cannot be consistent just by relying on code compilation, as is the case with APIs. To address this problem, Taro has bridged the differences between platforms by customizing a set of runtime standards. This set of standards is mainly composed of three parts, including the standard runtime framework, standard base component library, standard terminal capability API, wherein the runtime framework and API correspond to @taro/taro, component library corresponds to @tarojs/components. These standards are implemented in different terminals to bridge the difference. #### Multi-terminal adaptation basic standard - Basic framework (lifecycle, component APIs): Based on React’s life cycle and component APIs, supplemented by the features of mini programs - Standard component library (View, Button): Simulation implementation for all terminals with WeChat mini program component as the standard - Standard APIs (request, setState): Extended mini program standard APIs, simulation implementation for all terminals. The basic architecture diagram for multi-terminal adaptation is as follows:   ## Get started quickly #### Initialize the project Environment preparation: You need a node environment, and run the npm command: <center></center>  Start writing pages with Taro:  #### Run the project  #### Example of a multiplatform startup command:  To view the effect of three terminals at the same time: Just run the above commands separately; #### Conversion of WeChat native mini program to Taro mini program  #### Composition of a Taro project  #### Directory structure of a Taro project Basic directory structure:  Structure of a complete multi-terminal project:   For complete documentation, please visit: https://taro-docs.jd.com/ ## Multi-terminal adaptation #### Writing multi-terminal configuration files • project.config.json, WeChat’s configuration file, the content of which can customize the options of the WeChat mini program, the running directory and appid, etc.; • project.swan.json, the configuration file of Baidu mini program, the content of which is similar to WeChat; • project.jd.json, the configuration file of JD mini program, the content of which is similar to WeChat; • The mini programs of other platforms have independent configuration files to facilitate debugging.  #### Multi-terminal entry file Each platform has different page configuration information: • The page of WeChat mini program is a full page that contains WeChat login page (not required for other platforms); • Baidu mini program has a special login page. Some pages are not supported by Baidu and need to be hidden. For example: Image cropping, DaDa Now, printing, etc.; • JD mini program: Batch mailing is not supported, no login page is required, and subpackaging is not supported, all must be written into the main package; <center></center> #### Differential configuration - Corresponding files loaded for different platforms: - Differentiated configuration information for all platforms: - Map type; - Channel information; - Request header information; - 。。。 <center></center> #### Code differentiation ** Implemented by platform-specific JS code block, where the following syntax is added to any JS code **:  ** Implemented by platform-specific css code block, where the following syntax is added to any css code **:  Tips: The code is packaged without increasing the package size and is extracted for different platforms. #### Case of multi-terminal adaptation **Typical multi-terminal general solutions:** - Style parsing: - rpx for WeChat, vw for Baidu mini program, and px for JD mini program; - Taro uses px to convert the pixels to that of the corresponding platform through the framework. Therefore, singular px values should not be used; - The 1px (pixel) border is usually converted to a platform-specific unit, otherwise it will not be displayed. It is advised to use uppercase unit PX, for example: 1PX; - Baidu mini programs and JD mini programs do not support externalClasses, as is the case with other mini programs. Avoid using it; - Module import and export: - Modules shall be imported by ES6 import. Do not import JS files by require (not supported by some platforms); - Inline local image resources can be dynamically imported using require; - The url of external resources must be imported using https, which is not supported by some platforms or models; - The mini program plugins can be imported using require, but multi-platform adaptation and compatibility processing are required; - Component development details: - The key value of the component, index shall not be used, the id attribute of the object must be deconstructed first; - The atribute page is not updated when component rendering condition obtains the length. - Dataset: The datasets obtained by Baidu and WeChat are different, so lowercase should be used to keep the code consistent: For this camel-case: data-goodsIndex={index}, WeChat will be converted it to all lowercase goodsindex, while Baidu will retain this case, and follow the correct way: data-goodsindex={index}; **Notes for development of Baidu mini program:** - If the deeper state is not updated, the variables shall be de-constructed; - There might be deviation when converting to VW style to ensure the universality of style; - Height of individual components: Auto has a bug, neglect it; - There is a deviation in the centering of line-height, and it is safer to use flex; - The bottom of the fixed layout should be set to left: 0, bottom: 0, if not written, there will be a problem by default (default rendering in the middle); - The state may not be updated for deep-hierarchy mask component. Use tt-modal instead; - Image clipping, speech recognition, printing function, etc. are not supported by native APIs; - The state shall be explicitly set to null if it turns from stateful to stateless. For example, when hiding a list component: this.setState({list: null}) {list && <component instance >}; **Notes for development of JD mini program:** - Global override component style is not supported. If you want to be compatible with this style, you need to write it alone and add the splicing style name; - Mini program subpackaging is not supported, and page routing information shall be configured separately; - The showModal popup cannot customize the confirmColor attribute; - storagesync does not support storing json data, and manual JSON.parse is required for reading; - Canvas painting API is not supported: WeChat custom sharing function, image cropping, order barcode and other functions are not available; - Same-layer rendering is not supported, only Cover components can be used on native components; - ios has embedded H5. If the url is parameterized, you need to manually urlencode encoding; - The H5 page uses the webview of the mini program, which does not have all the webview functions of JD app, and some functions are not supported; - The URL shared by the JD mini program is different from the URL shared by other mini programs. Pay attention to the difference between the paths: - For example, shareURL: JD mini program: page/index/index WeChat mini program: /pages/index/index #### Multi-terminal synchronization debugging Configure in config/index.js: outputRoot: dist/${process.env.TARO_ENV}  ## Ecology and planning #### Logistics-style Taro UI component library – Tarot (adapted to Taro3.0)   #### Customized Taro template engineering Main features of template engineering: • It has Tarot component library and component usage examples introduced on demand. • It has tools from pandora-tools, such as gateway call plugins. • The login is adapted to multiple terminals, the mini program terminal automatically introduces the JD wireless login plug-in, the h5 terminal automatically redirects to the wireless unified login M page d, etc. • The gateway call is adapted to multiple terminals, with demo examples; • Contain more advanced APIs and usage examples such as TypeScript and Redux; • Other features will continue to be updated... #### Mini Debug for mini program MiniDebug is a multi-terminal debugging tool for mini programs, a tool library designed to improve the efficiency of mini program development and testing Features: The main features include context switching, identity mock, application information acquisition, location simulation, Redis management, scan, H5 redirection, and version update. The figure below shows part of page of the tool: It has been currently open sourced on GitHub (issue is welcome): https://github.com/jdlfe/minidebug  A logistics-style mini program visual drag-and-drop platform (under planning) JD Mall has implemented a mini program visual drag-and-drop platform: https://ling.jd.com/atom/cms/pc/06599  ## Conclusion: Taro V3.0.0 currently supports three types of frameworks: React, Nerv, and Vue. In the future, Taro will open up its expansion capabilities to allow developers to extend more framework support through Taro (for example, adaptation to Flutter will be possible). At present, the Taro features complete framework and active community. Even if there is no multi-terminal demand, it is a good choice to develop H5 only with Taro (it will be possible to access the mini program platform at zero cost in the future). For more practical experience about Taro 3.0, offline communication is welcome. ------------ ###### Programmer Language Specifications Tech-JDL ###### Author: Wang Chunyu, Consumer R&D Team, User Product Department ------------
Self-justification Tech
number of articles
196
reading volume
771724
Self-justification Tech
number of articles
196
reading volume
771724
添加企业微信
获取1V1专业服务
扫码关注
京东云开发者公众号