2
头图

Background At the beginning, we only made WeChat mini-programs. With the continuous expansion of our business and the rise of various program platforms, it is unrealistic to write a set of codes for each platform. Moreover, the native applet development model has many drawbacks.
In order to make applet development simpler and more efficient, we use Taro as the preferred framework, and we have sorted out the practical experience of using Taro, the main content revolves around what is Taro, why use Taro, and how to use Taro (correct posture). ), and some design ideas behind Taro to expand, so that everyone can have a complete understanding of Taro.
Taro 3.0 has gradually matured, and our project has been upgraded to Taro 3.0, so the code examples in this article are based on Taro 3.0.

What is TaroTaro

It is a multi-terminal unified development framework. Using taro, it can support the development method of React. By writing code that can run multiple terminals at one time, it can generate multi-terminal applications that can be used in various small programs, H5 and even React Native.
Taro official introduction: Taro is an open cross-end cross-framework solution that supports the use of React/Vue/Nerv and other frameworks to develop applications such as WeChat/JD.com/Baidu/Alipay/ByteDance/QQ applet/H5/React Native. Nowadays, there are various forms of terminals on the market. Various terminals such as Web, React Native, and WeChat applet are very popular. When business requirements are required to be expressed on different terminals at the same time, it is necessary to write multiple sets of codes for different terminals. The cost is obviously very high. At this time, the ability to adapt to multiple terminals by writing only one set of code is extremely necessary.

Its main features are: fast: can quickly develop applet: solve various pain points in applet development; more: can realize multi-terminal adaptation: a set of code adapts to multi-terminal such as applet, H5, RN, etc.;

Why use Taro
As applications become larger and more complex, the pain points of native applet development are gradually exposed:
•Complicated code organization: It is cumbersome to write a file structure of one page (up to four)
• Inconsistent specifications: components and method naming conventions are not uniform, various writing methods, and inconsistent grammatical structures are like React and Vue
• Weak string template: not strong in logical expression, does not support eslint
• Dependency management confusion: lack of npm package dependency management • Incomplete ES Next: only supports part of ES Next syntax, newer ES2020, ES2021+ are not supported • Outdated development methods: imperfect front-end engineering system, webpack packaging, CSS pre-processing The lack of processing, etc., is relatively backward for the front end, and it is not good for personal growth

Optional technical solutions Optional technical solutions For the above pain points of the WeChat applet development model, the industry also provides some optional solutions:

图片

图片
Comparative analysis
图片
mpvue is a framework developed by Meituan, the multi-terminal adaptation effect is not good, and the problem has not been maintained for a long time;
WePY is a componentized framework from Tencent, but it cannot adapt to multiple terminals;
Chameleon has outstanding performance in multi-terminal adaptation. The disadvantage is that it does not support Jingdong applet and cannot convert native applet (if you want to use it, you can only rewrite the project);
Taro's excellent features follow the React/Vue syntax specifications and introduce a modern development process, allowing development to focus more on core code and providing a sound code inspection method.

Multi-terminal needs
图片

Taro supports the most comprehensive platform, has unique conversion capabilities, and is superior to other frameworks in terms of performance. The characteristics are summarized as follows:
It can realize the conversion of WeChat applet native code to WeChat platform, Baidu platform, etc.;
The Taro framework is the only framework that realizes the adaptation of JD Mini Programs;
Support React/Vue syntax, better support for componentization and TypeScript;
The industry has great influence and the community is active. The framework of the research and development of Jingdong's internal excellent team is guaranteed, and the research and development team is reliable and supports our work very much;
A more complete UI component library, supporting multi-terminal synchronous debugging and adapting to more terminals;

Write in one place, run in many places

图片

The design idea mainly adopts the React development method

图片

Writing multi-terminal applications with React
图片

main idea

Code conversion: make code run on different platforms Runtime adaptation: make code behave the same on different platforms

Take WeChat applet as an example Take WeChat applet as an example

图片

JSX

图片

WXML

图片

Taro code compilation principle

图片

Taro's compilation principle: it is the process of parsing the input source code, building a syntax tree, and then converting the syntax tree and parsing to generate the target code.

The first is Parse, which parses the code into an abstract syntax tree (Abstract Syntex Tree), and then traverses and replaces the AST (this is not unfamiliar to the front-end, and can be analogous to the operation of the DOM tree) ), and finally generate, which generates compiled code based on the new AST.

Following the React syntax standard during development, combined with the idea of the compilation principle, a series of conversion operations are performed on the code file, and finally the code that can be run in the applet is obtained. React was originally born to solve web development, so with slight changes to the code, you can directly generate code that runs on the web side, and React Native, which is also under the React syntax system, can also provide support easily. Similarly for other platforms, such as Quick Apps, Baidu Mini Programs, etc., by compiling and converting the source code, the corresponding grammar code under the platform can also be obtained.
图片

图片

图片

图片

It can be seen that there are great differences between the component standards and API standards on the applet and the web. These differences cannot be smoothed out only by means of code compilation. For example, you cannot directly compile the applet directly into It looks similar, but their component properties are very different, and they cannot be consistent only by code compilation. Similarly, many APIs also face the same situation. In response to this situation, Taro uses a custom set of runtime standards to smooth out the differences between different platforms.

This set of standards is mainly composed of three parts, including standard runtime framework, standard basic component library, and standard end capability API. The runtime framework and API correspond to @taro/taro, and the component library corresponds to @tarojs/components. To achieve these standards at the end, so as to achieve the purpose of de-differentiation.

Multi-terminal adaptation basic standard basic framework (life cycle, component API):
Based on React's life cycle and component api, the features of the applet are used as a supplementary standard component library (View, Button): Based on the WeChat applet component as the standard, each end simulates the implementation of standard Api (request, setState): extended applet Standard Api, each terminal simulates the realization of multi-terminal adaptation The infrastructure diagram is as follows:

图片

图片

Quick start to initialize the project environment preparation: you need to have a node environment, run the npm command:
图片

图片

Start writing pages with Taro:

图片

run the project

图片

Example of a multiplatform startup command:

图片

If you see the three-terminal effect at the same time: run the above commands separately;
WeChat native applet conversion to Taro applet

图片
The composition of the Taro project
图片

Taro project directory structure Basic directory structure:
图片
A more complete multi-terminal project structure:
图片

图片
For complete documentation please visit: https://taro-docs.jd.com/

Multi-terminal adaptation

Multi-terminal configuration file writing • WeChat's configuration file project.config.json, the content of the file can customize the options of the WeChat applet, the running directory and appid, etc.;
• The content of the configuration file project.swan.json of the Baidu applet is similar to that of WeChat;
• The content of the configuration file project.jd.json of the Jingdong applet is similar to that of WeChat;
• Mini programs on other platforms have independent configuration files for easy debugging;

图片

multi-terminal entry file

Each platform has different page configuration information:
• The WeChat applet page is full, and there is a WeChat login page (not required for other platforms);
•Baidu applet has a special login page, some pages are not supported by Baidu and need to be hidden, such as: image cropping, Dada same city, printing, etc.;
• Jingdong Mini Program: batch mailing is not supported, no login page is required, and subcontracting is not supported, all must be written into the main package;

图片

Differently configure different platforms to load the corresponding files:
Differentiated configuration information for each platform:
map type;
channel information;
request header information;
. . .

图片
Code differential processing platform-specific js code block implementation, adding the following syntax to any js code:
图片
Platform specific CSS code block implementation, add the following syntax to any CSS code:
图片

Tip: The package size will not be increased when the code is packaged, and the corresponding code will be extracted for different platforms.

Multi-terminal adaptation cases Some typical multi-terminal general solutions:

Style parsing:
WeChat is rpx, Baidu applet vw, Jingdong applet px;
Taro uniformly uses px to convert the pixels of the corresponding platform through frame processing, so do not use singular px values;
The border of 1px (pixel) is usually converted to the corresponding unit of the platform, which will cause it to fail to display. You can use the uppercase PX unit, for example: 1PX;
Baidu Mini Programs and JD Mini Programs do not support externalClasses, and other Mini Programs may not support and avoid using them;

Module import and export:

Import modules need to use ES6 import, do not use require to JS files (some platforms do not support);
Inline local image resources can be dynamically imported using require; urls to import external resources must use https, some platforms or models do not support http;
You can use require to import applet plug-ins, but multi-platform adaptation and compatibility processing must be done;

Component development details:

The value of the component key, do not use index, the id attribute of the object must be deconstructed first;
The component rendering condition takes the length attribute and the page is not updated;
Dataset problem: Baidu and WeChat are different, so use lowercase to keep the code consistent: This kind of hump: data-goodsIndex={index}, WeChat will convert to all lowercase goodsindex, Baidu will keep hump, and write it correctly: data-goodsindex={index};

Notes for Baidu applet development:
When the deeper state will not be updated, the variable needs to be deconstructed;
The conversion to vw style is biased to ensure the versatility of the style;
Individual components height: auto has bugs, it's fine if you don't write it;
There is a deviation in the centering of line-height, and it is safer to use flex;
If the fixed layout is at the bottom, set left: 0, bottom: 0 , there will be a problem if it is not written by default (the default is rendered in the middle);
When the mask component level is deep, the state may not be updated, you can use tt-modal instead;
Image cropping, speech recognition, printing functions, etc. rely on native APIs not supported;
The state update needs to explicitly set null from existence to non-existence, such as hiding the list component: this.setState({list: null}) {list && <component instance>};

Notes for the development of JD Mini Programs:
Does not support global override component style, if you want to be compatible, you need to write it alone and add the splicing style name;
Small program subcontracting is not supported, and page routing information needs to be configured separately;
The showModal popup cannot customize the confirmColor property;
storagesync does not support storing json data, and reading requires manual JSON.parse;
Does not support canvas painting API: WeChat custom sharing function, image cropping, order barcode and other functions cannot be done;
The same layer rendering is not supported, only the Cover component can be used on the native component; ios has embedded H5, if the url has parameters, you need to do urlencode encoding manually;
The small program webview used on the H5 page does not have all the functions of the Jingdong app webview, and some functions are not supported;
The URL shared by JD Mini Programs is different from the URL shared by other Mini Programs. Pay attention to the difference of paths.

For example: shareURL: Jingdong applet: page/index/index WeChat applet: /pages/index/index

Multi-terminal synchronous debugging is configured in config/index.js: outputRoot: dist/${process.env.TARO_ENV}
图片

Ecological and planning logistics style Taro UI component library—Tarot (adapted to Taro3.0)

图片

图片

Customized Taro Formwork ProjectCustomized Taro Formwork Project

Main features of template engineering:
• Self-contained Tarot component library and component usage examples introduced on demand.
• Comes with tools in pandora-tools, such as gateway invocation plug-ins.
• The login is adapted to multiple terminals. The applet side automatically introduces the JD wireless login plug-in, and the h5 terminal automatically jumps to the M page d of the wireless unified login.
•Gateway invocation adapts to multiple terminals, with built-in demo example;
• Contains more advanced APIs such as TypeScript and Redux with usage examples;
• Other functions are continuously updated...

Mini Program Mini Debug Tool

MiniDebug is a multi-terminal applet debugging tool, a tool library designed to improve the efficiency of applet development and testing

Function introduction: The main functions include environment switching, identity mock, application information acquisition, location simulation, cache management, scan, H5 jump, update version, etc. The tool part page is shown in the following figure:

Currently open sourced on GitHub (issues are welcome): https://github.com/jdlfe/minidebug

图片

A logistics-style mini-program visual drag-and-drop platform (under planning)
Jingdong Mall has implemented a small program visual drag and drop platform: https://ling.jd.com/atom/cms/pc/06599

图片

Conclusion:
Taro V3.0.0 currently supports React, Nerv, and Vue frameworks. In the future, Taro will open up expansion capabilities, allowing developers to expand more framework support through Taro (for example, it will be possible to adapt to Flutter). At present, the Taro framework is perfect and the community is active. Even if there is no multi-end demand, it is a good choice to only use Taro to develop H5 (in the future, it can be connected to the applet platform at zero cost). If you want to know more about Taro 3.0 practical experience, you are welcome to communicate offline.


京东云开发者
3.3k 声望5.4k 粉丝

京东云开发者(Developer of JD Technology)是京东云旗下为AI、云计算、IoT等相关领域开发者提供技术分享交流的平台。