About the Taro

What is the Taro

Taro is a multi-terminal development solution framework tool developed by JDC bump Lab. It follows the React syntax specification and adopts the same componentalization idea as React. Develop with Taro for the same experience as React. Its component life cycle is exactly the same as React, and it also supports JSX syntax. By using the Taro framework tools, you only need to write a set of code to compile the source code to run on different applications (wechat, JINGdong, Baidu, Alipay, Bytedance applets, quick apps, H5, React-native, etc.) using Taro’s compilation tools.

To get started

You need to use the NPM or YARN tool for global installation. Taro development tool @tarojs/ CLI

Install the CLI using NPM/YARN/CNPM
$ npm/yarn/cnpm install -g @tarojs/cli
Copy the code

Once the installation is complete, use Taro’s init command to create template projects

$ taro init myDemo
Copy the code

In the process of creating a template project, you can select a template based on your daily development habits. At the same time, Taro will install the dependencies required by the project by default. The installation tool will check the dependencies in the sequence of YARN > CNPM > NPM. You need to install the corresponding dependencies yourself using the installation tool in the project directory.

This is the whole process of using Taro to create projects. A simple init command helps us complete all the operations. All you need to do is select the appropriate template to create projects.

A little introduction

What is xiao Yi

“Xiaoyi Comes” is a small program of logistics service developed for the purpose of investigating customers’ evaluation of the existing services of the logistics side and the urgent needs of the future, aiming at the drawbacks of the logistics side colleagues’ inability to supervise the quality of terminal delivery personnel and track and feedback of logistics services after the recipient signs for the order. It solves the whole life cycle operation of purchasing terminal for enterprise business division customers, including logistics tracking, order inquiry, signing, evaluation and invoice tracking, after-sales application and other functions.

An overview of

The project has now gone through four iterations and is now fully online.

The first phase of Phase ii The third phase of Phase iv
Home page Order to evaluate Home page redesign Distribution list
Personal center Sweep the code to sign for Invoice query After application
My order
Logistics tracking
Electronic signature form

As a developer, I have experienced four iterations in the development process is also deeply impressed. During the whole process from the establishment of each iteration of the project to the completion of the project development and the launch of the project, I deeply felt the serious and responsible attitude of the product students. It can be said that they treated the product as their baby and took care of it carefully. Feel the careful thinking of interaction students, design the perfect product of students; I felt the positive attitude of the r & D students, and was very helpful in the process of cooperating with the development joint investigation. I felt the rigor of my classmates and tested the whole process with the intention of not making any difference. This is the birth of a product of the whole process, each step contains our people’s hard work, I believe that whether the user or our own will be very cherish our small easy.

Projects show

Technology selection

The Taro framework tool is selected to be used for the development of the “Easy to Come” widget project, which is completed with the Taro UI component library. The reason why we do not choose to use the native wechat widget for development is that the Taro framework has the following advantages by comparison.

Quick learning
  1. NPM can not be used to manage third-party libraries in the development process of native wechat small programs, and some relatively new ES specifications can not be used. Taro, however, supports installation and management of third-party dependencies using NPM/YARN, ES7/ES8 or even the newer ES specification, self-configurable, CSS precompiler, and state management using Redux.

  2. Taro these related features and our consistent project development work at ordinary times, especially the students often use the React technology stack development projects, through the use of Taro framework to develop a small program, we no longer need to go to learn native WeChat development language specification, reducing the costs of learning, but also improve the development efficiency. As part of the Taro team’s ongoing development iterations, the multi-terminal framework Taro has now released its 3.0 RC version, which now supports the Vue language. Subsequent projects can choose from React/Vue.

Rich Taro UI component library

It is well known that there is no supporting component library for native small program development, and the components used in the project development process are completed by the developers themselves. This is a relatively tedious process for developers, but it will increase the complexity of project development and affect the development efficiency. However, Taro has a multi-terminal UI component library based on its own development – Taro UI. It currently has most of the general business components, can be in wechat/JINGdong/Alipay/Baidu xiaoprogram, H5 and other multi-terminal adaptation, provides friendly API, can be flexibly configured and used. Taro UI currently has only one set of default theme colors. To meet the diverse visual needs of businesses, there are three ways to customize the theme (SCSS variables override the globalClass Global Style class/configure the customStyle attribute). See the official documentation for details. With the Taro UI component library, we no longer need to worry about business components and greatly improve our development efficiency.

Support multi-side development transformation

At present most of the project will involve multiterminal, including native, H5, each platform of small programs, especially the big customer business, we are now docking easily need three-terminal running at the same time online, for we need to focus only on the front end developers H5 and small procedures, the cost of many different side to write the code clearly is very high, The Taro framework allows you to write only one set of code through Taro’s compilation tool. Compile the source code to run in different terminals (wechat/JD/Baidu/Alipay/Bytedance applet, Kuaiapp, H5, React-native, etc.).

To sum up: Using the Taro framework to develop small programs, not only reduces our learning cost, but also helps improve our development efficiency by cooperating with the Taro UI, especially for the need to run multi-terminal projects, a set of code perfect for multi-terminal transformation, can only say really delicious, Taro you are worth having.

Problems encountered

Believe that most developers would lightly in the process of project development at ordinary times some of the more difficult problems, for the first time using Taro framework me concern the development of the program, a lot sure enough does have a few problems in the development process, every time meet this kind of situation will give yourself to a three even: don’t panic, settle down, no big problem. After a series of operation attempts, these problems were solved one by one.

Order search

There is a requirement function for searching orders at the top of the list page of small programs. We introduce the basic component Input in the Taro framework to realize the function of searching. It seems to be a very common function, but in the process of development and use, we found the following problems:

First we introduce the Input base component, and then listen for its onInput event. After entering the search keyword, the Input will listen to the content of the Input box and trigger the onInput event to make corresponding response. During this process, we will find that the event will be triggered as long as the Input content, and the background interface is frequently called. The page performance deteriorates or even freezes. So we added timers to do the processing, through throttling to achieve delayed search. Although we do throttling processing, it seems to realize delayed search, and the background interface is no longer frequently called, but in Chinese search, we find that the interface will be called as long as the Chinese input process is interrupted. We all know that in H5 development we can distinguish between Chinese and English by listening for the two events compositionStart and compositionEnd, but we found that these two apis do not exist in the applets Input component.

<Input className='search-input' placeholder={this.props.placeholder} value={this.state.value} onInput={this.handleChange} 
 />
 handleChange = (e) => {
    this.timer && clearTimeout(this.timer);
    this.timer = setTimeout(() => {
        let value = e.target.value
        this.setState({ value });
        if(! value) { this.handleClear();return;
        }
        const { onSearch } = this.props;
        onSearch && onSearch(value);
        clearTimeout(this.timer)
    }, 1000);
}
Copy the code

In order to avoid this problem, we do not conduct real-time search any more. Instead, we will trigger the search when users actively click the complete or search button. After checking the official document of the Taro base component Input, we find that in addition to the onInput Api, there is an onConfirm event in this component. By monitoring this event, the problem of real-time search can be perfectly avoided. Meanwhile, most searches of H5 project are rarely real-time search. It is suggested that the follow-up searches in the mini program should also be initiated by users.

<Input className='search-input' placeholder={this.props.placeholder} value={this.state.value} onConfirm={this.handleChange} 
 />
 handleChange = (e) => {
    let value = e.target.value
    this.setState({ value });
    if(! value) { this.handleClear();return;
    }
     const { onSearch } = this.props;
     onSearch && onSearch(value);
}
Copy the code

The pits that are embedded in the H5

In the small easy to the top of the first screen of the wheel is the H5 chain, to run the H5 page in the small program, need to be embedded in the web-view. Taro framework we directly into the WebView can be used.

import Taro from '@tarojs/taro';
import { View,webView} from '@tarojs/components';
class webview extends Taro.Component {
	constructor() { super(... arguments); this.state = { url:' '
		};
	}
	componentDidMount() {
        this.setState({
            url:decodeURIComponent(this.$router.params.url)
        })
	}
	render() {
	    return( <View> <web-view src={this.state.url}/> </View> ); }}Copy the code

The following points need to be paid attention to in H5:

1. A project can only have one WebView.

2. The SRC property of the web-view component, as shown in the figure above, is used to set web links, but it should be noted that the SRC of the web-view must be configured with HTTPS links.

3. As long as the web-view component is configured with a link, it is fully screened and automatically jumps. Therefore, I use it as a separate routing page, and obtain the URL of the external chain as a parameter by triggering the click event at the position of the first screen of the wheel broadcast graph.

4. The domain name of the interface to which web-view jumps must be set in the service domain name list set by the applet development. Otherwise, the interface cannot be accessed.

5. Web-view external chain URL need to decode, or it may lead to garbled or parameter loss problem (encodeURIComponent(URL), decodeURIComponent(URL))

NavigateTo ({url: '/pages/webview/webview? url=${jumpUrl}`}); } // webView is embedded with page H5componentDidMount() {
    console.log(2,this.$router.params.url)
    this.setState({
        url:decodeURIComponent(this.$router.params.url)
     })
}
Copy the code

NavigateTo ({url: '/pages/webview/webview? url=${jumpUrl}`}); } // webView is embedded with page H5componentDidMount() {
    console.log(2,this.$router.params.url)
    this.setState({
        url:decodeURIComponent(this.$router.params.url)
     })
}
Copy the code

Project optimization

Wechat small program is not the product of native development, its rendering carrier is not a native client, is still the browser kernel. Compared with traditional web pages, wechat applet opens a two-thread model. A single thread is used to render the UI view layer, and a separate thread is used to execute JS logic and control the display of the view layer. Thread between the time delay of data transmission will be there, that is a small program between view layer and logical layer of communication is asynchronous operations, at this time will be facing page rendering speed, the first screen load white during the emergence of a series of problems, such as small in order to improve program performance, to avoid these problems we have adopted a series of solutions.

Component granularity refinement

Known now everyone in promoting development of modular, praise highly modular development is not to say that to every small module to refine the extracted components, if for custom component granularity is too detailed, for yourself is a relatively complicated and tedious process, for other developers, the program code readability becomes very unfriendly. Within each component has its own independent nodes and their corresponding logic, if for custom component granularity is too thick, too much internal logic components, will influence the efficiency of the old and the new node diff inside the component, thus rendering performance data, so for the custom component refinement should still should hold an appropriate degree.

In the small easy to small program in our component processing of the list page of data items, search, data for empty prompt page, selection page, which mainly introduces the next search component, the component reuse to the order list page, electronic signature page, after-sales application page, invoice query page; First developed a phase of the project only have the function of search, order list page didn’t extract the search component, in the later project iteration involves the invoice query, after-sale application pages and so on all need search functionality, we extract it as common components, which is described above component refinement need particular case is particular analysis, There are many pages that need to reuse this component in the project. At the same time, each page can extract it as a common component without adding distinguishing logic or only needing to add little distinguishing logic when reusing this component. For example, the search component in Xiaoyi only needs to distinguish the default search text displayed.

By properly handling component refinement, it can not only reduce the scope of influence when data is updated, but also support component reuse, which is a relatively suitable scheme for projects. There is no specific provision for the degree of component refinement. Specific projects need specific analysis. Remember not to excessively split components, otherwise the readability of the overall code of the project will become extremely poor.

Image resource optimization

Image resources occupy a large amount of traffic in the mobile terminal system, and the same is true in small programs. Especially for loading the list page with related commodity images, optimizing the loading of image resources can effectively accelerate the response time of the page and improve the rendering speed of the page.

Use WebP format images
  1. WebP is a Google image file format that supports lossless/lossless compression. According to the official description, WebP lossless compression is 26% smaller than PNG and lossless compression is 25-34% smaller than JPEG. At present, the rendering of most item lists is returned by the background interface, and then the front-end gets the corresponding data for rendering. The format of returned images is usually.jpg or.png. In order to optimize the image resources, the front-end can only handle relevant operations. In general, there are two ways to deal with the format of the picture. One is to cache the URL of the picture and then render it after format replacement. The other is to replace the formatting directly when the list is rendered.

  2. In the Xiaoyi project, we made a comparison between the returned image format and the processed image format, and found that the size of the original.jpg image was 37.3KB, and the size of the processed.webp image was 15.7KB, almost 40% difference in volume. By changing the original image format to WebP format, the image volume is reduced, the server pressure is reduced, and the rendering performance is improved.

<Image className='good-img' src={(imageHost + sku.imgUrl).replace(/.jpg/g,'.webp')} lazy-load="true"/>
Copy the code

Note: make sure the server has webP image resources, otherwise the image will not render (you can use the image source address in onError event for compatibility)

Lazy loading of images

For picture lazy loading believe that every developer is not strange, about its principle here is no longer redundant. No matter in the native wechat applet or the Image component in the Taro framework, there is a built-in Api to support lazy Image loading — lazy-load, which is not started by default and needs to be configured by users themselves. Note that this applies only to images under page and Scroll view.

Virtual list

Most of the list pages in our normal development are loaded in scrolling pages, with a fixed number of pages loaded each time, and we render them all at once. For the list with a large amount of rendering data, it will lead to certain performance problems and the hidden danger of page gridlock. To solve this hidden problem, we need to render the visual area instead of the full rendering. The list data of the non-visual area should be rendered after scrolling to the visual area, which is similar to the lazy loading of pictures. The Taro framework provides a built-in component, named Virtual List, to address this problem. The component is built into the Taro framework and can be used in React/Vue, various applets and H5 applications. To use it, we simply import the VirtualList component into the corresponding page.

The import VirtualList from ` @ tarojs/components/virtual - list ` < VirtualList height = {500} the height of the list / * * / width ='100%'ItemCount ={dataLen} /* itemSize={100} /* itemSize={100} / / </VirtualList>Copy the code

Data preloading

Data prepull (the pre-loading in Taro) can pull business data from third-party servers in advance through wechat background when the small program is cold started. When the code package is loaded, the page can be rendered more quickly, reducing the waiting time of users, and thus improving the opening speed of the small program. Its principle is actually to store the response data in the local client in advance for the front end of the applet to retrieve. When the applet is loaded, you only need to call the API getBackgroundFetchData provided by Taro to obtain data from the local cache.

In xiaoyi applet, the list page does not add the operation of data pre-pull, but only tries to carry out the operation of pre-pull when some pages jump. Are not on the list page to pull of data, because the data pull though can improve page rendering speed, but also has certain disadvantages, because the data request is made by WeChat backend server, request to the data will be in the local cache time, not for the period of validity of the cache time to initiate the request, This will cause a certain risk for the list frequently updated in real time, so we only do the pre-pull operation when jumping in part of the page that does not need to update data frequently in real time in the small program.

In order to obtain the server data rendering page as soon as possible, we usually send requests to obtain the background server data within the life cycle of the page componentWillMount. We should know that the route jumps to the corresponding page until the page loading is completed. Small program to complete the environment initialization and page instance initialization of a series of operation, will produce certain time consuming at this time, in order to effectively avoid this part of the time, we take the routing to jump to the page, before is Taro. The call request before navigateTo will jump to the page of interface, the request to the data cache, The data is stored in the Redux state manager and can be read directly from the Redux state Manager after the next page is loaded. In this way, the page can get the corresponding data rendering quickly when loading, which improves the page rendering speed and reduces the waiting time.

Taro also provides the componentWillPreload hook, which accepts the parameter of the page jump as a parameter. $this.$preloadData (); $this.$this.$preloadData (); It is important to note that the jump method is called using absolute paths. Relative paths do not trigger this hook.

conclusion

The project is the first time I’ve used Taro + Taro UI to develop a small program, by looking at the official documentation, online research methods such as solved some problems encountered in the process of development, in the project development at the same time joined the performance improvement solutions, through the contrast test before substantial increase in performance, oneself is also fruitful, Benefited a lot. At present, Xiaoyi is still in the iteration stage. I have tried to use Hooks development in the previous requirement development of the distribution list, and I plan to use Hooks development in the subsequent requirement iteration and transform the previous page into TS+Hooks development. The Taro Framework is also in constant iteration. Since 2.2, The Taro framework has introduced a plug-in mechanism, allowing developers to write plug-ins to extend the functions of The organization and customize them for their businesses. The recently released version 3.0 candidate also supports the use of the Vue language. As a tool framework to support multi-terminal transformation, it is worth choosing.