background

Recently, I received multi-terminal development, because the old project used React. Considering the migration cost, I chose Taro. The migration cost is relatively low, and it is fast to get started.

Taro and uni – app

I did my research and there are many good and mature open source frameworks out there. Among them, Taro and Uni-App, as the two “elite” frameworks, have their own merits and offer me more choices.

For a comparison, see the following nuggets article:

  • Taro vs UNI-APP selection comparison experience

Taro

Considering the cost of migration mentioned above, I finally choose Taro. The following mainly introduces the use of Taro and the summary of functions in the migration.

The official documentation of Taro is very comprehensive. Basic operations can be completed with the official documentation (address of the official documentation).

At present, there are only two business scenarios in my project, namely wechat small program and H5, so the technical exploration is mainly aimed at these two ends, and the article is also mainly used for the summary of these two ends.

New project

CLI Tool Installation

# NPM install -g@tarojs/CLI # OR use yarn to install CLI $yarnglobal$CNPM install -g@tarojs /cliCopy the code

Project initialization

Create a template project using the command

$ taro init myApp
Copy the code

NPM 5.2+ can also create template projects using NPX without a global installation

$ npx @tarojs/cli init myApp
Copy the code

Install dependencies

$CD myApp install dependency $YARN install dependency $CNPM install dependency $NPM installCopy the code

After the installation is complete, the file structure has been generated as follows:

Compile command

NPM script $NPM run dev: $NPM run build: eAP // H5 # YARN $ yarn dev:h5 $ yarn build:h5 # npm script $ npm run dev:h5 $ npm run build:h5Copy the code

React Framework for project migration

Choose the framework

Since I usually use the React framework for development, I directly chose the React framework during migration. This selection is made during project initialization as shown below:

The program

Directly copy the file, and then adjust, the main adjustment content has the following parts

UI framework adjustments

The original project used ANTD-Mobile. After the migration, it was changed to @antmjs/vantui. Some component names and the usage of components are slightly different.

Take the following page

  • The List component in ANTD-Mobile is not available in @antmjs/vantui, so we need to rewrite this part of the code;
  • Button component has two UIs, but there are differences in attributes, which can be modified.
// import { List, Button } from 'antd-mobile'; import { Button } from '@antmjs/vantui'; // AntD-mobile List component uses const listContent = content => {return (<div className='content-list'> <List> {content.list.map(item => { return ( <List.Item className={classnames({ 'list-item-baseline': item.btnName })} prefix={materiaIcon[item.type]} key={item.type} description={item.btnName ? btnConten(item) : null}> <div className={classnames({ required: item.required })}>{item.name}</div> </List.Item> ); })} </List> </div> ); }; Const listContent => {return (<View className='content-list'> {content.list.map(item => { return ( <View key={item.type} className='content-item'> <View className='flex'> <Icon color='#007af5' name={materiaIcon[item.type]} size='20px' /> <View className={classnames('ml5', { required: item.required })}>{item.name}</View> </View> {item.btnName ? btnContent(item) : null} </View> ); })} </View> ); }; // AntD-Mobile Button component used <Button color='primary' block shape=' Rectangular ' <Button type="primary" block={true}> </Button>Copy the code

Page jump method

Native H5 jumps use the push or replace methods provided by the History object. Use the routing API provided by Taro. I wrote a common method to do this for jumps.

/** * @param {string} path app.config.js full address for example /pages/home/index */ commonNavigateTo(path) {** @name bottom navigation route list */ const switchList = ['/pages/home/index']; if (switchList.includes(path)) { Taro.switchTab({ url: path, }); } else { Taro.navigateTo({ url: path, }); }}Copy the code

HTML tags

Previously, Taro V3.3 did not support the use of HTML tags. Instead, they used tags such as View and Text provided by Taro, which are detailed in the Taro component library.

import React, { Component } from 'react'
import { View, Text } from '@tarojs/components'

export default class C extends Component {
  render () {
    return (
      <View className='c'>
        <Text>c component</Text>
      </View>
    )
  }
}
Copy the code

Taro V3.3 + supports the use of HTML tags, requires plug-in configuration.

Configure the plug-in

1. First download and install the plugin @tarojs/plugin-html

yarn add @tarojs/plugin-html
Copy the code

2. Then add the use plug-in to the project configuration

// config/index.js
config = {
  // ...
  plugins: ['@tarojs/plugin-html']
}
Copy the code

Note:

  • If you encounter unsupported tags, you can use the components provided by Taro. See the Taro Component library for details.

Native applet for project migration

Later, there is a plan to use Taro to develop the native small program project into multiple applications, but there is no actual application yet. After the actual application, I will update it, and I predict that I will encounter some interesting problems.

Develop a compass

I will inevitably encounter various problems in the development process, but it has also become my “touchstone”, I have encountered problems, solutions, detailed list for JYM reference, some solutions may not be optimal, welcome the big man to provide better solutions.

The forward route is faulty

The methods provided by Taro are basically the same as those provided by the mini-program, which can be seen in the documentation.

It is important to emphasize the integrity of the redirect URL, that is, the URL should start with a right slash, otherwise it may be treated as a relative route.

The wrong sample

Taro.navigateTo({
  url: 'pages/order/index',
});
Copy the code

An error is as follows

errMsg: “navigateTo:fail page “pages/order/orderStatement/pages/order/index” is not found”

The correct sample

Taro.navigateTo({
  url: '/pages/order/index',
});
Copy the code

Small program file too large processing method

1. Enable compression as prompted

Set NODE_ENV to production to enable compression. Example: $ NODE_ENV=production taro build --type weapp --watchCopy the code

2. The subcontract

Subcontracting restrictions are as follows, official documentation

  • The whole small program all subcontracting size is not more than 20M
  • The size of a single subcontract/main package cannot exceed 2M

Since our project wasn’t that big, we didn’t actually use it, but I found a few good references on nuggets:

Small Program Subcontracting (Taro Subcontracting Case)

Jingdong shopping small program | Taro3 project subcontracting practice

3. Vendors. Js is too large

The vendor.js file contains common dependencies for node_modules in addition to Taro, which can be oversized for some reason.

Here are the main reasons why the vendor.js file is so large in my project

3.1 introduced Crypto-JS

The solution is to either lower the crypto-js version or put crypto-js-min locally (83KB).

Taro. Request Specifies the solution for the header that cannot be customized on the H5 host

Due to some special business logic of my project, I must add custom headers. However, H5 Taro. Request does not support custom headers (supported by apples-to-apples-to-apples-to-apples-to-apples-to-apples-to-request).

/ * * * @ description asynchronous request distribution H5 and small program to use the different * / import $from '/ request - weapp'; import $2 from './request-h5'; export function requestFunc() { if (process.env.TARO_ENV === 'weapp') { return $; } else { return $2; }}Copy the code

User-defined routes on the H5 end during the migration of old projects

Because the old project has some external entry, such as extrapolation links, third-party entry, etc., so the migration should be compatible processing.

1. Route the page before processing

Before processing, the following page routing is automatically generated by the Taro framework, which is obviously inconsistent with the old project

https://{{domain}}/pages/index/index (Browser mode)

2. Customize page routing scheme 1

Solution 1 is to configure H5.Router. CustomRoutes in the way provided by Taro

config/index.js

module.exports = { // ... h5: { // ... Router: {customRoutes: {// "customRoutes ":" customRoutes "'/pages/index/index': '/index', '/pages/detail/index': ['/detail'] // You can configure multiple custom routes for a page using arrays}}}}Copy the code

Pros: Less logic.

Disadvantages: 1) It is easy to leak when there are too many pages to configure. 2) If you forget to add new pages, the page may not be found.

3. Customize page routing scheme 2

Write your own custom page routing code logic

app.js

import resetRouter from '@utils/resetRouter'; ComponentDidMount () {// =>true: componentDidMount() {// =>true: If (process.env.taro_env === 'H5 ') {resetrouter.resetrouter (); }}Copy the code

utils/resetRouter.js

*/ import Taro, {Current} from '@tarojs/ Taro '; /** * import Taro, {Current} from '@tarojs '; @param {Object} taroAppConfigInit project configuration item @return {Array} The final pagePath Array */ const getTabBarPageList = taroAppConfigInit => { const tabBarInit = taroAppConfigInit.tabBar ? taroAppConfigInit.tabBar : {}; const tabBarList = tabBarInit.list ? tabBarInit.list : []; const tabBarPageList = []; if (tabBarList.length ! == 0) { tabBarList.forEach(item => { tabBarPageList.push('/' + item.pagePath); }); } return tabBarPageList; }; @param {Object} taroAppConfigInit project configuration item @return {Array} Final Array Array */ const getAllPagesList = taroAppConfigInit => { const allPagesListInit = taroAppConfigInit.pages ? taroAppConfigInit.pages : []; let allPagesList = []; allPagesListInit.forEach(item => { allPagesList.push('/' + item); }); return allPagesList; }; @param {Array} allPagesList All route Array * @param {string} pathName Current page route * @return {Boolean} The final Boolean value  */ const getNoFoundFlag = (allPagesList, pathname) => { let flag = true; if (allPagesList.includes(pathname)) { flag = false; } return flag; }; @param {string} PathName; @return {Boolean} Reconfigured route */ const resetPathname = pathname => { let pathnameInit = ''; if (pathname.indexOf('pages') === -1) { pathnameInit = '/pages' + pathname + '/index'; } else { pathnameInit = pathname; } return pathnameInit; }; /** * Jump to tabBar page with switchTab, NavigateTo * @param {string} pathName * @param {string} search current page route parameter */ const switchTabOrnavigateTo = (pathname, Search) => {// hide configuration window.__taroappConfig (including all contents of app.config.js) const taroAppConfigInit = current.app.config? Current.app.config : {}; const allPagesList = getAllPagesList(taroAppConfigInit); const tabBarPageList = getTabBarPageList(taroAppConfigInit); const pathnameInit = resetPathname(pathname); console.log(pathnameInit, 'pathnameInit'); TabBar if (tabbarPagelist. includes(pathnameInit)) {return Taro. SwitchTab ({URL: pathnameInit,}); //=>true: If the route type is tabBar if (tabbarPagelist. includes(pathnameInit)) {return Taro. } else { const noFoundFlag = getNoFoundFlag(allPagesList, pathnameInit); const url = noFoundFlag ? '/pages/dispatch/nofound/index' : pathnameInit + search; return Taro.navigateTo({ url: url, }); }}; /** * const resetRouter = () => {/** * const resetRouter = () => { pathname, search } = window.location; switchTabOrnavigateTo(pathname, search); }; export default { resetRouter };Copy the code

Disadvantages: Need to write their own logic, add extra work.

Advantages: Handles all page routes at once, does not need to add again, and adds 404 redirection.

UI framework

We chose the awesome @Antmjs/Vantui based on Taro’s UI framework. The UI framework provides a rich set of components and covers the usual functionality, but its API documentation is a bit simpler, and I may write a summary of its use later.

conclusion

All things are difficult at first, but nothing is difficult if you put your heart into it.

Open source framework is a precious resource to promote the development of technology, there are maintenance costs in the pit, so you can change your thinking, do their own compatible treatment, for example, some problems can be handled by the environment, although a little cumbersome, but help to solve the problem.