Some time ago in the next development of a micro channel small program, the development process summed up some I think useful tips for me, extracted, equivalent to a summary of the double disk, also hope to help you. If it helps, don’t forget to like it 🌟 ~

  1. Wechat Developer Tool Version:1.03.2006090(2020-06-19)
  2. Base library version:v2.12.1 (2020-08-04)

1. Possible pits and Tips during development

Originally wanted to write a small skill, the result I summed up a pile of pits, did not have to imagine before the micro channel small program development experience is so bad, so bad, from micro channel developer tools to the so-called “new language”, there is a thick semi-finished five namely visual sense, really let me emmm…. In addition, I found that most of the small program articles on the Internet are how to use and how to avoid the pit of practical text, rather than skills, which also reflects the pit from the side of the small program.

In native WeChat small program development process, I keep getting this question “why open a dime of tencent technology talents, will launch so laji”, many places of retarded against humanity, in two or three years ago, the community has been put forward, the official response has feedback is under repair, but a few years later, still no tidings, The official response is still a frosty “feedback” 😤

  1. Wechat developer tools often hot update does not work or even white screen, recompile is not good, can only forcibly exit after opening again;
  2. Similar to the previous one, sometimes a little style error, preview the entire white screen, debugger does not say where the problem, directly give you discard therapy does not show, recompile can not solve the problem, only forced to exit after opening again;
  3. Similar to the previous one, the debugger reported the error is often not useful, the donkey head is not the horse mouth, making it difficult to locate the problem;
  4. When the Android terminal custom Tabbar is pulled down to refresh, it will also move down with the screen, and it is impossible to bypass the Bug, the custom Tabbar style has been written I changed to the own Tabbar!
  5. importPaths that do not support absolute paths, such as those you wish to referenceutils/fetch.jsIn no matter how deep the component you have to go slowly../Go to the root directory, same thing.wxssfile@importYou can only use relative paths when importing files, so it appears. /.. /.. /.. /.. /.. /utils/fetch.jsThis kind of thing;
  6. Static resource paths cannot have Chinese characters. If they have Chinese characters, they cannot be loaded.
  7. .wxsThe file does not support ES6 and must be written in crappy ES5.
  8. .wxmlCan only be introduced in.wxsFile cannot be imported.jsFile??
  9. The template{{}}Even methods can not be executed, only to handle simple operations such as+ - * /, if data needs to be encounteredfilterThe scene that needs to be in.jsThe file is preformatted and then one by onesetData“, such as often written[2,3,4].includes(type)Can’t even run!
  10. .wxsNot available in the fileDateObject, so nonew Date(), can only use lamegetDateThe same is true for regular objects, which are used to generate regular objectsgetRegExpfunctiongetRegExp(pattern[, flags]);
  11. .wxsCan call others in.wxsFile, and can only be called by require.wxsFiles, imported files must use relative paths;
  12. setDataI don’t even bother to do an object merge ifdata: {a: {b: 1, c: 1}}, thensetData({a: {b: 2}})Will be losta.cI mean, it’s really infuriating, andsetData({['a.b': 2]})That’s how it works;
  13. On the IOSDateObject to get arbitrary time parameters such asgetDay,getTimeNaN because the IOS Date constructor doesn’t support it2018-04-26The date in this format must be converted to2018/04/26This format will display properly;
  14. Development version of the small program sometimes requests inexplicably sent out, the upper right corner of the three point enable debug to open “development debugging” after inexplicably can send a request, in many mobile phones are like this, unknown truth.

2. Wechat request promiseization

2.1 Use off-the-shelf libraries

Install the Promise library WX-Promise-Pro, make sure to include -S or –production, otherwise the build will fail.

npm i -S wx-promise-pro
Copy the code

Then in app.js:

import { promisifyAll } from 'wx-promise-pro'

promisifyAll()  // promisify all wx api

App({ ... })
Copy the code

After that, it can be used normally:

wx.pro.showLoading({
    title: 'Loading'.mask: true
})
  .then(() = > console.log('in promise ~'))
Copy the code

2.2 Self-implementation

In fact, we can implement such a library ourselves, the principle is very simple, using the native API wX.request as an example:

// Native API usage
wx.request({
    url: ' '.// The requested URL
    data: {},    / / parameters
    method: ' './ / post and get
    success: res= > {
        // Request success callback with res as the callback parameter
    },
    fail: res= > {
        // The request failed callback function. Res is the callback parameter}})Copy the code

If we promiseize it, we want it to be called in the following way:

// The expected usage of promiser
wx.pro.request({
    url: ' '.// The requested URL
    data: {},    / / parameters
    method: ' '   / / post and get
})
  .then(res= > {
      // Request success callback with res as the callback parameter
  })
  .catch(res= > {
      // The request failed callback function. Res is the callback parameter
  })
Copy the code

And the then function returns a Promise object, making it possible to keep calling it in the chain, so we first need new to come up with a Promise object:

function request(opt) {
    return new Promise((resolve, reject) = >{ wx.request({ ... opt,success: res= > { resolve(res)},
            fail: res= > {reject(res)}
        })
    })
}
Copy the code

We can further improve the code by passing in the resolve and reject methods as the arguments for success and fail are only executed by the resolve and reject methods.

In addition, since the native APIS of other small programs are in the same format, we can use the curization method to handle other PROMISeized apis:

function promisify(api) {
    return (opt = {}) = > {
        return new Promise((resolve, reject) = >{ api({ ... opt,fail: reject,
                success: resolve
            })
        })
    }
}
Copy the code

Then, mount the result of the curlized method execution on the wX. pro object as the new Promiseized API:

// Promise the specified API
wx.pro.request = promisify(wx.request)

/ / usewx.pro.request({... }) .then(...)Copy the code

Then to make it easier for us to use other methods, we can loop to mount promiseizable methods on wX objects such as Request, scanCode, showToast, getUserInfo, and so on to wX. pro objects. You can use wX.pro.xx directly. Since this method execution returns a Promise object, it can be used just like any other promiseized object.

In fact, before we knew it, we had implemented the source code for WX-Promise-Pro ourselves, and the core code of the library was the lines above 🥳

2.3 Use in projects

With the above tools, we can use them in the project. In order not to spread wX.request or WX.pro.request throughout the project, we can simply wrap them here. Create two new files as follows:

// utils/ API /fetch. Js encapsulates the request method, request interceptor

const app = getApp()

const BaseUrl = 'http://172.0.0.1:7300/mock'

const TokenWhiteList = [
    '/app/user/get-by-code'     // The API that does not require authentication is manually added here
]

/** * Set the request interceptor@param Params request parameter */
const fetch = (params = {}) = > {
    // Interceptor logic
    if(! TokenWhiteList.includes(params.url)) { params.header = {'content-type': 'application/json'./ / the default value
            'token': app.globalData.token || ' '}}if (params.url.startsWith('/')) {    // Concatenate the full URL
        params.url = BaseUrl + params.url
    }

    / / return promise
    returnwx.pro.request({ ... params }) .then(({ data: { code, message, data } }) = > {
          / /... Logical handling of various exception cases
          // Return normal when code 20000 is agreed with the backend
          if (code === 20000) return Promise.resolve(data)
          return Promise.reject(message)
      })
}

export { fetch }
Copy the code

Then encapsulate all the apis into a single file for centralized management:

// utils/ API /apis. Js encapsulates all request apis

import { fetch } from './fetch'

/* Obtain user information according to wechat code */
const appUserGetByCode = ({ code } = {}) = > fetch({
    url: '/app/user/get-by-code'.data: { code }
})

/* Scan code to log in */
const appUserQrLogin = ({ qrCode } = {}) = > fetch({
    method: 'POST'.url: '/app/user/qr-login'.data: { qrCode }
})

/* Personal information */
const appUserInfo = () = > fetch({
    url: '/app/user/info'
})

/* Obtain system parameters, data dictionary */
const appSysParamListByParam = () = > fetch({
    url: '/app/sys-param/list-by-param'
})

/* All */ in the data dictionary
const appSysParamListAll = () = > fetch({
    url: '/app/sys-param/list-all'
})

export {
    appSysParamListAll,   // All data dictionary
    appSysParamListByParam,   // Obtain the system parameter, data dictionary
    appUserGetByCode,   // Obtain user information according to wechat code
    appUserQrLogin,   // Scan the code to log in
    appUserInfo   // Personal information
}
Copy the code

Where you want to use the API, you can introduce it like this:

import * as Api from '.. /.. /utils/api/apis.js'   // Relative path

// Usage mode
Api.appSysParamListAll()
  .then(({ dataList }) = > this.upData({ sysParamList: dataList }))
  .then(() = > {
      const keyList = this.data.sysParamList.map(T= > T.key)
      this.upData({
          keyList,
          formData: { keys: keyList }
      })
  })
Copy the code

Use way is very comfortable, here use upData, is the following I would like to introduce the content, is the next very recommended small program tool ~ 🥳

3. SetState modifies the properties of the object you want to modify in data

In small programs, data cannot be manipulated directly. You need to use the setData function. In view of the micro channel small program development setData use experience is very poor, I use a library function WX-UPdata, this library function is very helpful to me in the development, here specially recommended to you.

3.1 Why use WX-UPData

Do you sometimes feel uncomfortable when using setData? Here’s a simple example:

/ / your data
data: {
    name: 'Crayon Shin-chan'.info: { height: 140.color: 'yellow'}}Copy the code

If you want to change info.height to 155, here’s what to do with setData:

// This removes all other properties from the info
this.setData({ info: { height: 155}})// You need to take out the info object and modify the whole setData
const { info } = this.data
info.height = 155
this.setData({ info })
Copy the code

This doesn’t seem too complicated, but if data is a large object, you need to change the deeper and different objects and array items one by one:

data: {
    name: 'Crayon Shin-chan'.info: {
        height: 140.color: 'yellow'.desc: [{ age: 8 }, 'Favorite elephant Song'.'handsome', { dog: 'white'.color: 'white'}}}]Copy the code

For example, if you want to change the height of info.desc to 155, change the age of the 0th item to 12, and change the color of the 3rd item to gray?

// Fetch the object to be changed, change the number and setData back
const { info } = this.data
info.height = 155
info.desc[0].age = 12
info.desc[3].color = 'grey'
this.setData({ info })

// Or, as in some articles, it is not very readable or practical
this.setData({
    'info.height': 155.'info.desc[0].age': 12.'info.desc[3].color': 'grey'
})
Copy the code

The above two methods are often used in our ordinary small programs, compared with other Web framework, it is very lame, a thick semi-finished feeling oncoming, there is no such a method:

this.upData({
    info: {
        height: 155.desc: [{ age: 12}, {color: 'grey'}]}})Copy the code

This method will help you change the value of the property in the nested object, skip the items in the array that you don’t want to change, and only set the properties and items that you provide. It will skip a lot of crappy code, and it will also be very readable.

Is that why I used WX-upData instead of setData in the project that went live

The principle behind WX-UPData is simple. Here’s an example:

this.upData({
    info: {
        height: 155.desc: [{ age: 12}]}})// Will be automatically converted to the following format,
// this.setData({
// 'info.height': 155,
// 'info.desc[0].age': 12,
// })
Copy the code

Originally, we had to do this manually, but now WX-UPdata does it for us, isn’t it beautiful?

3.2 WX-upData Usage

In general, we can mount the method directly to the Page constructor, so that we can use upData in the Page instance just like we use setData:

// app.js
import { updataInit } from './miniprogram_npm/wx-updata/index'  // Your library file path

App({
    onLaunch() {
        Page = updataInit(Page, { debug: true})}})// Use in the page code
this.upData({
    info: { height: 155 },
    desc: [{ age: 13 }, 'handsome boy'].family: [,, [,,,, {color: 'grey'}}]])Copy the code

While some frameworks may make further modifications to the Page object, replacing the Page directly may not be a good idea. Wx-updata also exposes the tool methods, which users can use directly in the Page code:

// In the page code
import { objToPath } from './miniprogram_npm/wx-updata/index'  // Your library file path

Page({
    data: { a: { b: 2}, c: [3.4.5]},

    // Wrap it yourself
    upData(data) {
        return this.setData(objToPath(data))
    },

    // In your method or lifecycle function
    yourMethod() {
        this.upData({ a: { b: 7}, c: [8.9]})}})Copy the code

Wx-updata provides a Symbol type for Empty and an object path for the array. For more information, see the wX-upData documentation. You can also refer to < Developing wechat mini program >. Why I gave up setData and used upData> in this introductory article.

In addition, the use of WX-UPdata can also use the original setData, especially sometimes to empty the array, flexible use, can get a better small program development experience, I wish you a happy small program development 🤣

4. Use SCSS to write styles

4.1 Webstorm Configuration Methods

As for the crappy.wxss style, I used webStorm’s file watcher tool to listen for changes in SCSS files and compile them into.wxss files in real time. It was easier to use. Here is my configuration:

Then remember to include styles to ignore in the.gitignore file:

*.scss
*.wxss.map
Copy the code

When you upload to Git, you don’t need to upload SCSS files. If your team members need SCSS, you are advised to add SCSS files to git.

With this setup, a component locally looks like this

The.js,.json,.scss, and.wxml files are the ones we need to focus on. The.wxss file is automatically generated and updated when you change the.scss file. The.wxss.

If you are not using Webstorm, you can directly run the command sass –watch index. SCSS :index. WXSS -s expanded. If the command line is closed, the sass command will not listen for file changes and then compile.

Similarly, you can use precompiled languages such as Less and Stylus.

4.2 Configuring Visual Studio Code

The universal VSC can also do this, search for and download the easy Sass plugin, and then modify/add the configuration in setting.json:

"easysass.formats": [{"format": "expanded"."extension": ".wxss"
  },
  {
    "format": "compressed"."extension": ".min.wxss"}]Copy the code

The preceding expanded is the compiled.wxss file, and the following compressed is the.wxss style file. You can delete the following configuration and add the intermediate style to the.gitignore file to omit:

*.scss
Copy the code

Of course, you can not add, if your colleagues are also practical SCSS to develop small programs, other as above, so you can be happy to use SCSS in small program development

5. Use iconFont

In Web development, iconfont can be described as the most commonly used flexible iconfont tool, here is how to introduce iconfont icon in wechat small program.

First find the ICONS you want to use, click on the shopping cart and download them to your local.

Copy the iconfont. CSS file to the styles folder of the wechat mini program (in the following custom, you can also put it where you want, such as fonts) and change the suffix to.wxss

To introduce styles in app.wxss:

@import "styles/iconfont.wxss";
Copy the code

Then you can use the icon you just added in.wxml, using the I tag for the Web and the text tag for the applet:

<text class="iconfont icon-my-edit" style="color: blue"></text>
Copy the code

If you want to add a new icon, download the new iconfont. CSS file and rename it locally and override it, and go through the process again.

Of course, if the style library you are using provides some ICONS that meet your requirements, it is better not to import an external icon font file, but in most cases it is not sufficient 🤣


Online posts are mostly different in depth, and even some inconsistent, the next article is a summary of the learning process, if you find mistakes, welcome to leave a message, if this article helped you, don’t forget to support oh (collection don’t like, are playing rogue 🤣) ~

Reference documents:

  1. Youngjuning/WX-Promise-Pro: ✨ powerful and elegant wechat small program asynchronous library 🚀
  2. Small program development pit -IOS time displayed as NaN – Mo xiaofei
  3. [wechat small program] Performance optimization
  4. Wechat applet uses Promise-Short book
  5. Why do I give up setData and use upData – Nuggets to develop wechat applet

Other highly praised articles by the author:

  1. JS can improve happiness tips
  2. Vue use tips
  3. Nginx from introduction to practice, 10,000 words in detail!
  4. Half an hour to do CentOS entry-level basic knowledge
  5. Hand in hand Webpack multi-entry configuration practices
  6. Basic principle of front-end route hops

PS: my blog address Github – SHERlocked93/blog, welcome everyone to pay attention to my public number front afternoon tea, direct search can be added, continue to push for everyone front, as well as the front end of the surrounding quality technical text, common progress, refuting together ~