Use Taro-a quick and easy way to develop your business

Posted Jun 16, 202015 min read

About Taro

What is Taro

Taro is a framework tool for multi-end development solutions created by JDC·Bump Lab . It follows the React grammar specification and adopts the componentization idea consistent with React. Using Taro for development can get the same development experience as React. Its component life cycle is completely consistent with React, and it also supports JSX syntax. By using the Taro framework tool development, only need to write a set of code can use Taro's compilation tool to compile the source code separately can be on different ends(WeChat/Jingdong/Baidu/Alipay/Bytebeat applet, fast application, H5 , React-Native, etc.) running code.

Get started

First, you need to use npm or yarn tools for global installation. Taro development tools @tarojs/cli

# Install the CLI using npm/yarn/cnpm
$npm/yarn/cnpm install -g @tarojs/cli

After the installation is complete, use Taro's init command to create a template project

$taro init myDemo

In the process of creating a template project, you can choose the corresponding template according to the habits of your daily development project. At the same time, Taro will install the dependencies required by the project by default. The tools used for installation will be tested in the order of yarn> cnpm> npm. An interruption or failure occurs during the installation of dependencies. You need to use the installation tool in the project directory to install the corresponding dependencies.

image

The above is the overall process of using Taro to create a project. A simple init command helps us complete all the operations. In the creation, you only need to select the corresponding template. Taro will default to the dependencies that developers need to install the project. It can be said to be fast, convenient, simple but not simple.

Xiaoyi Introduction

What is Xiaoyi

'Xiao Yi Lai' is aimed at investigating the customer's evaluation of the existing services on the logistics side and the drawbacks such as the fact that the recipient cannot complete the quality supervision of the terminal delivery personnel and track the logistics services after the order is signed by the recipient. In the future, there is an urgent need for small logistics service programs that are developed. It solves the operations of the entire life cycle of the procurement terminal for customers in the enterprise department, including logistics tracking, order query, signing, evaluation, invoice tracking, after-sales application and other functions.

Overview

The project has now undergone four iterations and is now fully online.

Phase I Phase II Phase III Phase IV
Home Order Evaluation Homepage Revision Delivery List
Personal Center Scan code for receipt Invoice query After-sales application
My Order
Logistics Tracking
Electronic receipts

As a developer, I have also been deeply touched during the four-phase iterative development process. From the overall process of each iteration of the project to the completion of the online development of the project development, I deeply felt the serious and responsible attitude of the product classmates. It can be said that this product is treated as its own baby, and it is taken care of carefully; Think carefully and design the perfect production of the students; feel the positive attitude of the R&D students, and they are also quite awesome in the process of coordinating the development and coordination; feel the rigor of testing the students, and test the entire process in the original intention of not being a bit at all. This is the whole process of the birth of a product. Every step contains the hard work of us. I believe that both users and ourselves will cherish our Xiaoyi.

image

Project display

image

image

Technical selection

Xiao Yi Lai was selected to use the Taro framework tool to develop the small program project, which was completed with the Taro UI component library. The reason why I did not choose to use the native WeChat applet for development is that through comparison, the Taro framework has the following advantages.

Quick start
  1. In the development process of native WeChat applets, npm cannot be used to manage third-party libraries, and some newer ES specifications cannot be used. However, Taro supports the use of npm/yarn to install and manage third-party dependencies, supports the use of ES7/ES8 and even newer ES specifications, can be configured by itself, and supports the use of CSS pre-compilers and Redux for state management.
  2. These related characteristics of Taro are enough to coincide with our usual project development work, especially for students who often use the React technology stack to develop projects. By using the Taro framework to develop small programs, we no longer need to learn the native WeChat development language again. Standardize, reduce the cost of learning, and also improve the development efficiency. In the continuous development iteration of the Taro team, the multi-end framework Taro has released the 3.0 RC version and has begun to support the Vue language. React/Vue can be freely selected for subsequent project development.

image

Rich Taro UI component library

It is well known that there is no supporting component library for the development of native applets. The components used in the project development process are all completed by developers themselves. This is a relatively cumbersome process for developers, and it will increase the complexity of project development for projects. Degree, affecting development efficiency. However, Taro has a multi-terminal UI component library based on its own development-Taro UI. It currently has most of the common business components, which can be run on WeChat/Jingdong/Alipay/Baidu applets, H5 and other multi-terminal adaptations, providing friendly APIs. , Can be used flexibly. Taro UI currently has only one set of default theme colors. In order to meet the diversified visual needs of the business, there are currently three ways to customize the theme(SCSS variables override globalClass global style class/configure customStyle attribute), the specific usage can be viewed Official documents . Through the use of the Taro UI component library, we no longer need to worry about business components, greatly improving our development efficiency.

image

Support multi-end development and transformation

At present, most projects will involve multi-end, including native, H5, and small programs on various platforms, especially the large client business we are now docking. All three terminals need to be running at the same time. For our front-end developers, we only need to pay attention to H5. Compared with small programs, the cost of writing multiple sets of code at different ends is obviously very high. For the disadvantage of time-consuming and labor-intensive adaptation for multi-end development, the Taro framework only needs to write a set of code. The source code is compiled through Taro's compilation tools. Compile the code that can be run on different terminals(WeChat/Jingdong/Baidu/Alipay/Byte Jump Applet, Kuai application, H5, React-Native, etc.).

In summary:using the Taro framework to develop small programs not only reduces our learning costs, but also helps to improve our development efficiency by cooperating with the Taro UI, especially for projects that require multi-end operation, a set of code is perfectly adapted Multi-end transformation, can only say true fragrance, Taro you deserve it.

Problems encountered

I believe that most developers will encounter some more difficult problems in the usual project development process. I am also worried about the first time I use the Taro framework to develop small programs. As expected, I did encounter them during the development process. Some problems, every time you encounter this situation will give yourself a three-connected:don't panic, stabilize, the problem is not big. After a series of operation attempts, these problems were finally solved one by one.

image

At the top of the small program list page, there is a search order demand function. We introduced the basic component Input in the Taro framework to implement the search function. It seems to be a very common function, but it was found during the development and use process. The following questions:

First, we introduce the Input basic component, and then listen to its onInput event. After entering the search keyword, Input will respond to the onInput event by listening to the content of the input box, and in the process we will find that as long as the input content This event is triggered, and the background interface is frequently called, resulting in a decrease in page performance or even a stuck phenomenon. Therefore, we added a timer to do the processing, and realized the delayed search through throttling. Although we have compared the throttling process, it seems that it implements delayed search and no longer calls the background interface frequently, but when searching in Chinese, we found that the interface will be called as long as it is broken during the input of Chinese. We all know that it is developed in H5. You can distinguish between Chinese and English by monitoring the two events compositionstart and compositionend in the Input monitor, but we found that these two APIs do not exist in the APIs of the Applet 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);
}

image

image

In order to circumvent this problem, we no longer conduct real-time search, and use the user to actively click the completion or search key to trigger the search, and return to the official document query of the Taro basic component Input. It is found that this component has an onConfirm event in addition to the onInput Api By monitoring this event, the problem of real-time search is perfectly avoided. At the same time, most H5 project searches are rarely real-time searches. It is recommended that the search in subsequent applets also use the user to actively trigger the search.

<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);
}

image

Those pits with embedded H5

At the top of Xiaoyi's first screen, the carousel is the H5 link. To run the H5 page in the applet, it needs to be embedded in the web-view. In the Taro framework, we directly introduce webview to use.

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>

       );
    }
}

In the small program, the foreign chain H5 should pay attention to the following points:

  1. There can only be one webview for the same project.

  2. The attribute src of the web-view component, as we can see in the above figure, src is used to set the web page link, but it is worth noting that the src of web-view must be configured with the https protocol link;

  3. As long as the web-view component is configured with a link, it is full-screen and automatically jumps, so I will use it as a routing page alone, and obtain the URL of the external link by triggering the click event at the position of the first screen carousel map. Pass in as a parameter.

  4. The interface domain name for web-view jump needs to be configured in the business domain name list set by the applet development, otherwise it will not be accessible.

  5. The url of the web-view external link needs to be decoded, otherwise it may cause garbled characters or parameter loss(encodeURIComponent(url), decodeURIComponent(url))

    //Home
    jumpLink(jumpUrl) {

     console.log(1, jumpUrl)
     Taro.navigateTo({url:`/pages/webview/webview?url=${jumpUrl}`});

    }
    //webview embedded H5 page
    componentDidMount() {

     console.log(2,this.$router.params.url)
     this.setState({
         url:decodeURIComponent(this.$router.params.url)
      })

    }

image

//Home
jumpLink(jumpUrl) {
    console.log(1, jumpUrl)
    Taro.navigateTo({url:`/pages/webview/webview?url=${jumpUrl}`});
}
//webview embedded H5 page
componentDidMount() {
    console.log(2,this.$router.params.url)
    this.setState({
        url:decodeURIComponent(this.$router.params.url)
     })
}

image

Project optimization

The WeChat applet is not a product of native development, its rendering carrier is not a native client, it is still the core of the browser. Compared with traditional web pages, the WeChat applet has a dual-threaded model. A separate thread is used to render the UI view layer, and another separate thread is used to execute JS logic to control the display of the view layer. There will be a certain delay in the data transmission between threads, that is to say, the communication between the view layer and the logic layer of the applet are asynchronous operations, at this time, you will face the page rendering speed, the first screen is loaded with a white screen, etc. The emergence of a series of problems, in order to improve the performance of small programs, to avoid these problems, we have adopted a series of solutions to this.

image

Component granularity refinement

As we all know, everyone is advocating componentized development. The advocacy of componentized development does not mean that every small module must be refined to extract components. If the granularity of custom components is too fine, it is an item for yourself. The relatively complicated and tedious process will make the readability of the project code unfriendly for other developers. Each component has its own independent node and its corresponding logic. If the granularity of the custom component is too coarse and the internal logic of the component is too much, it will affect the efficiency of the new and old nodes diff inside the component, thereby affecting the performance of data rendering. Therefore, it is still necessary to grasp an appropriate degree for the refinement of custom components.

In Xiaoyilai, our componentized processing of data items with a list page, search, data is empty prompt page, selection item page, which mainly introduces the search component, which is reused to the order list page, electronic Sign-in page, after-sales application page, invoice query page; initially, only the order list page had a search function during the first phase of the project development. At that time, the search component was not extracted, and the invoice query and post-sale application page were involved in the later project iterations. The search function is required before we can extract it as a common component. This is the detailed analysis of the components described above, which requires specific analysis. There are many pages that need to reuse this component in the project, and each page reuses this component. When there is no need to add distinguishing logic or only a little distinguishing logic can be extracted as a common component, such as the search component in Xiaoyi, only the default search copy displayed can be distinguished.

image

Through proper processing of component refinement, it can not only reduce the scope of data update, but also support component reuse, which is a relatively suitable solution for the project. There is no specific regulation on the degree of component refinement. Specific projects require specific analysis. Remember not to split components excessively, otherwise the readability of the overall code of the project will become extremely poor.

Picture resource optimization

Image resources occupy a large amount of traffic in the mobile system, and are the same in small programs, especially for loading list pages with related product images. Optimizing the loading of image resources can effectively speed up the page response time and improve the page Rendering speed.

Use WebP format pictures
  1. WebP is a picture file format introduced by Google that supports lossy/lossless compression. According to the official description, WebP lossless compression volume is 26%smaller than PNG, and lossy compression volume is 25-34%smaller than JPEG. At present, most of the project list rendering is related data returned by the background interface, and then the corresponding data is obtained by the front end for rendering. The format of the returned image is often .jpg or .png format, for the returned image format If you want to optimize the picture resources, only the front end can handle the related operations at this time. For picture format processing, we generally have two methods. One is to cache the picture url and perform format replacement before rendering; The format is directly replaced when the list is rendered.

  2. In the Xiaoyi project, we compared the returned image format with the processed image format and found that the original .jpg format image size was 37.3KB, and the processed .webp format image size was 15.7KB. The volume can almost reach the gap of 40%. Through processing, the original image format is changed to the webp format, which reduces the size of the image, reduces server pressure, and improves rendering performance.

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

Note:Make sure that there is a webp format picture resource on the server, otherwise the picture will not be rendered(you can use the picture source address for compatibility processing in the onError event)

Picture lazy loading

I believe that every developer is no stranger to lazy image loading, and the principle of it will not be repeated here. Whether it is in the native WeChat applet or the Image component in the Taro framework, it has built-in Api-lazy-load that supports lazy loading of images. It is not enabled by default and needs to be configured by the user. One thing to note is that it is only for page It is valid with the image under scroll-view.

image

Virtual List

Most of the list pages in our usual development are loaded by scrolling and paging, each time loading a fixed number of items, for each number of items we load, we are rendering them in full at one time. Rendering a list with a large amount of data will cause certain performance problems, and there is a hidden danger of page jams. To address this hidden problem, we need to render the visualization area instead of full rendering, and the list data of the non-visual area is scrolling. Rendering after reaching the viewable area is similar to lazy loading of pictures. In response to such problems, the Taro framework encapsulates a built-in component named Virtual List(Virtual List, this component is now built in Taro, which can be used in React/Vue or various applets and H5. When using it, we directly Introduce the VirtualList(VirtualList) component to the corresponding page.

import VirtualList from `@tarojs/components/virtual-list`
  <VirtualList
    height={500} /* The height of the list */
    width='100%' /* The width of the list */
    itemData={data} /* data of rendering list */
    itemCount={dataLen} /*Length of render list */
    itemSize={100} /* The height of the list item */
  >
  </VirtualList>

image

Data preloading

Data pre-pull(pre-loading in Taro) can pull business data from a third-party server in advance through the WeChat background when the applet is cold-started. When the code package is loaded, the page can be rendered faster, reducing user waiting time. Thereby increasing the opening speed of the applet. 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, just call the API getBackgroundFetchData provided by Taro to get the data from the local cache.

The list page does not add the data pre-fetching operation in the Xiaoyi applet, but only tries to perform the pre-fetching operation when part of the page jumps. The reason why the data is not pre-pulled on the list page is because although the data pre-pull will increase the rendering speed of the page, there will be certain drawbacks. Because the data request is sent by the WeChat background server, the requested data will be There is a certain cache time locally, and the request will not be re-initiated within the validity period of the cache time, which will cause a certain risk to the frequently updated list in real time, so we only need to update the data in real time in some parts of the Xiaoyi applet. The page did a pre-pull operation when jumping.

In order to get the server data as soon as possible to render the page, we usually send requests to get the background server data during the life cycle of the componentWillMount of the page. We need to know that the route jumps to the corresponding page until the page is loaded. To complete a series of operations for environment initialization and page instance initialization, a certain amount of time will be generated at this time. In order to effectively avoid this part of time, we take before the page route jump, that is, before calling Taro.navigateTo Request the interface of the page to be redirected to, cache the requested data, and store it in the Redux state manager. After the next page is loaded, read the data directly from the Redux state manager, so that it can be guaranteed The page quickly gets the corresponding data rendering when loading, which improves the page rendering speed and reduces the waiting time.

In addition, Taro also provides the componentWillPreload hook, which receives the parameters of the page jump as parameters. You can return the content that needs to be preloaded by return, and then you can get the preloaded content through this.$preloadData after componentWillMount is triggered on the page. One thing to note is that you need to use an absolute path when calling the jump method, the relative path will not trigger this hook, the specific use can refer to [preload]( http://taro-docs-in.jd.com/docs/optimized -practice).

image

to sum up

This project is the first time I used Taro+Taro UI to develop small programs. I solved some problems encountered during the development process by consulting official documents and online research. At the same time, I added performance improvement aspects to this project development. The solution has achieved a considerable improvement in performance before testing and comparison, and he has also been very productive and benefited a lot. At present, Xiaoyi is still in the iteration period. In the previous development of the distribution list requirements, I have tried to use Hooks development. During the subsequent demand iterations, I plan to use all Hooks development and transform the previous page into TS+Hooks development. At present, the Taro framework is also constantly being iterated. Since 2.2, Taro introduced a plug-in mechanism that allows developers to write more plug-ins to expand more functions for Taro or customize personalized functions for their own businesses. The recently released 3.0 The candidate version also supports the use of Vue language, as a tool framework that supports multi-end conversion is worthy of everyone's choice.