preface

Applets open up cloud development capabilities, giving developers the ability to quickly build applets back end services, and are also interested as a front end that doesn’t rush into new technologies;

Taro is a multi-end development solution based on React grammar specifications launched by Bump Lab. Compared with MPVUE or WEPY, Taro is young and has more pits, but it is suitable for people like me who tend to develop with React (for specific comparison, please refer to the technical analysis and selection of small program development framework).

I combined the two, used Cheerio and superagent to grab the use case.jp, and developed a Japanese Use Case Assistant. Because IT was just for practice, the writing was rough, and I was still shamelessly hoping to get a star 🤟


Introduction on the pit

Cloud development report

  • Environment set up

Cloud development can be created in two ways:

  1. Create a project using QuickStart (the Fast Start template for cloud development)

    In this way, we will create a small program base template named miniProgram with cloud development invocation examples and a directory named CloudFuntions to store cloud functions in the directory at the same time, from which we can start a new project;

  2. Use cloud development based on existing applets

    Create a folder under the applet directory as your cloud functions directory, then add the field “cloudfunctionRoot” in the project.config.json file: “Your cloud function directory”, that is, you can see the icon of the directory in the wechat developer tool becomes cloud, create cloud function in this directory;

  • Cloud function writing

When you use wechat developer tool to create a cloud function in the cloud function directory, you will create a directory based on the name, which contains an index.js and package.json.

Call the cloud function in the applet as follows

wx.cloud.callFunction({
    name: 'Cloud function name',
    data: {
      key1: 'value1',
      key2: 'value2'
    }
}).then((res) => {
    console.log(res);
}).catch((e) => {
    console.log(e);
});
Copy the code

The entry function for index.js looks like this:

// Cloud function entry function
exports.main = async (event, context) => {
    Key1, event.key2, event.key2, event.key1, event.key2
    const { key1, key2 } = event;
    return { query: { key1, key2 } }
}
Copy the code

Each cloud function can be treated as a separate service. If you want to install third-party dependencies, just right-click on the directory, choose open in the terminal, and NPM install dependencies

It is important to note that each cloud function is independent and the required dependencies require NPM install in the corresponding directory, which can make the project very large and inelegant. So, let me introduce the TCB-Router

  • Tcb-router is used to manage routes

Tcb-router is developed by Tencent Cloud team, based on koA-style small program · Cloud development cloud function lightweight class routing library, mainly used to optimize the processing logic of server functions.

The way to use the TCB-Router is simple

const TcbRouter = require('tcb-router');
exports.main = (event, context) = > {
    const app = new TcbRouter({ event });
    app.router('Route name'.async (ctx) => {
        // The original event needs to be obtained through ctx._req.event
        const { param1, param2 } = ctx._req.event;
        ctx.body = { key1: value1 };
    });
})
Copy the code

At this point, the invocation mode of the small program also needs to be changed to:

wx.cloud.callFunction({
    name: 'Cloud function name',
    data: {
      $url: 'Route name'// Other data param1:'test1',
      param2: 'test2'}, success: res = > {}, fail: err = > {console. Error (` [cloud function] [${action}', err)}})Copy the code

Taro article

  • Environment set up
npm install -g @tarojs/cli
taro init myApp
Copy the code
  • In the pit of
  1. Insufficient Api support

Since Taro does not support some of the new apis in wechat, such as wx.cloud, which is required for cloud development, it is possible to use the wx variable directly for pre-test, but esLint will alert you to this, so you can add the following code to the.eslintrc file;

"globals": {
  "wx": true
},
Copy the code
  1. You cannot manipulate JSX arrays using methods other than Array#map

  2. Do not pass JSX elements (taro/no-jsx-in-props) in the JSX argument (props)


The crawler article

  • superagent

Superagent is a very useful HTTP request module, used to crawl web pages very useful, very simple to use, here is the code I use to crawl yourei.jp:

// const superagent = require('superagent');
// ...
function crawler(url, cb) {
  return new Promise((resolve, reject) = > {
    superagent.get(url).set({
      'User-Agent': 'the Mozilla / 5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
    }).end(function (err, res) {
      if (err) {
        reject(err);
        return;
      }
      resolve(res);
    });
  });
}
Copy the code
  • cheerio

Cheerio is a lightweight, flexible, jquery-like tool for analyzing HTML elements. Cheerio is easy to use and efficient for some server-side rendered pages and simple little page crawls.

After using superAgent to crawl the web content, you can parse the page code as follows

    // const cheerio = require('cheerio');
    // ...
    const result = crawler(apiUrl).then((res) = > {
      // After using load, $can be used as jquery selector to select elements
      const $ = cheerio.load(res.text);
      const categories = [];
      $('[data-toggle]').each((i, ele) = > {
        // You can use.text(),.html(), and so on to get the content of the element
        categories.push($(ele).attr('href'));
      });
      return {
        list: categories,
      };
    });
Copy the code

conclusion

  • Taro

If you are a React developer and need to develop multiple miniprograms, or if you want to migrate your React projects to miniprograms, Taro is a good choice, but there are still a lot of holes to fill, and hopefully it will get better and better

  • Development of cloud

If you are an individual developer and want to try small program development but don’t want or have trouble building your own server, cloud development is a good choice, easy to get started and very agile.

However, cloud development may be charged later. If you don’t have your own server, cloud development can be used as a transition period. I hold the attitude of watching its development.

reference

Applets cloud development documentation

Tcb-router reference document

Taro multi-terminal unified development framework