Use Labrador 0.3 to build ES6 / ES7 standard modular WeChat applet

Labrador is a modular front-end development framework developed for WeChat applets

In the article WeChat Mini Program Development Three Deadly Crimes and Solutions , I explained to you three disadvantages of WeChat Mini Program development, and provided the Labrador framework to solve these drawbacks.

In the previous version of Labrador, some functions of component reuse are not perfect. Today Labrador released version 0.3. Compared with the previous version, it provides more powerful component functions and changes some module interfaces.

The following is the getting started manual for Labrador version 0.3.x. If you have built a project based on the old version of Labrador, please refer to the instructions below for the corresponding upgrade project and upgrade the global labrador-cli library to version 0.3.


QQ Exchange Group 282140496


characteristic

  • Using the Labrador framework can make WeChat developer tools support loading massive NPM packages

  • Support ES6 / ES7 standard code, using async / await can effectively avoid callback hell

  • Component reuse, the second package of WeChat applet framework, to achieve component reuse and nesting

  • Use Editor Config and ESLint to standardize code style, which is convenient for team collaboration

installation

npm install -g labrador-cli

Initialize the project

mkdir demo
cd demo
npm init
labrador init

Project directory structure

demo                 # 项目根目录
├── .babelrc         # babel配置文件
├── .editorconfig    # Editor Config
├── .eslintignore    # ESLint 忽略配置
├── .eslintrc        # ESLint 语法检查配置
├── package.json
├── dist/            # 目标目录
├── node_modules/
└── src/             # 源码目录
    ├── app.js
    ├── app.json
    ├── app.less
    ├── components/  # 通用组件目录
    ├── pages/       # 页面目录
    └── utils/

Note that all files in the dist directory are generated by the labrador command, please do not modify it directly

Configure development tools

After the project is initialized, use the IDE you are accustomed to, such as WebStorm or Sublime, to open the project root directory. Then open the micro-letter web developer tools new projects, local development directory to select distthe destination directory.

Development Process

Sublime waiting WebStorm or edit IDE srcdirectory of source code, and then run in the project root directory in labrador buildorder to build the project, then the micro-letter web developer tools left menu, click debug interface of the restart button to see the effect.

We in the development, micro-channel web developer tools is only used for debugging and preview, do not micro-letter web developer tools to modify the code editing interface.

Micro-letter web developer tools will occasionally go wrong, the performance of click Restart unresponsive buttons, error debugging console output can not require a large number of files, edit the interface code files are not displayed. This is because the labrador buildcommand updates the entire distdirectory, and micro-letter web developer tools will be abnormal change in the monitoring of the code, in which case only need to turn off the micro-letter web developer tools restart can be.

We can also use the labrador watchcommand to monitor srcthe code directory, automatically builds when changes without editing code after every run manually labrador build.

So the best posture is:

  1. Run in the project labrador watch

  2. Coding in WebStorm, save

  3. Switch to the micro channel web developer tools debugging, preview

  4. Back to coding in WebStorm

  5. ...

labrador library

labradorLibrary of global wxvariables package, most of the wxmethods were the object Promise support, in addition to on*the beginning or at *Syncthe end of the method. Use the following code in labradorthe library.

import wx from 'labrador';

We do not recommend re-use wx.getStorageSync()such as synchronous blocking method, and in the asyncuse of functions await wx.getStorage()to improve performance asynchronous non-blocking method, except in special circumstances.

app.js

src/app.js The sample code is as follows:

import wx from 'labrador';
import { sleep } from './utils/util';

export default class {
  globalData = {
    userInfo: null
  };

  async onLaunch() {
    //调用API从本地缓存中获取数据
    let logs = await wx.getStorage({ key: 'logs' }) || [];
    logs.unshift(Date.now());
    await wx.setStorage({ key: 'logs', data: logs });
    this.timer();
  }

  async timer() {
    while (true) {
      console.log('hello');
      await sleep(10000);
    }
  }

  async getUserInfo() {
    if (this.globalData.userInfo) {
      return this.globalData.userInfo;
    }
    await wx.login();
    let res = await wx.getUserInfo();
    this.globalData.userInfo = res.userInfo;
    return res.userInfo;
  }
}

The ES6 / ES7 standard syntax is used throughout the code. The code does not need to be declared use strict, because at compile time, all code will enforce strict mode.

Code does not call the global App()methods, but the use of exportgrammar default export a class, after compilation, Labrador will automatically increase App()method calls, all calls do manual App()method.

Custom component

Labrador's custom components are based on WeChat applet framework components, further customized combinations, with logical processing and style. The purpose of this see the micro-channel program to develop three small sins and solutions

General project custom components stored in src/compontentsa directory, a file composed of three general components, *.js, *.xmland *.lessrespectively correspond to the micro channel small framework js, wxmland wxssfiles. In Labardor source project, we deliberately adopted xmland lesssuffix to show the difference.

Custom component example

The following is a simple custom component code example:

logic src/compontents/title/title.js

import wx from 'labrador';
import randomColor  from '../../utils/random-color';

export default class Title extends wx.Component {
  data = {
    text: '',
    color: randomColor()
  };

  handleTap() {
    this.setData({
      color: randomColor()
    });
  }
}

layout src/compontents/title/title.js

<view class="text-view">
  <text class="title-text" catchtap="handleTap" style="color:{{color}};">{{text}}</text>
</view>

style src/compontents/title/title.less

.title-text {
  font-weight: bold;
  font-size: 2em;
}

The code is very similar to the page in the WeChat applet framework. The biggest difference is in the logic js code does not call the global Page()function declaration page, but with a exportsyntax derived a default class that needs to inherit and labrador.Componentassembly base class.

Note component incident response methods must handlebegin with! For example, abovehandleTap

page

We require that all pages must be stored in pagesthe directory, subdirectory for each page of the file format and custom components consistent, but may be more of a *.jsonconfiguration file.

Page example

Here is the sample code for the default homepage:

logic src/pages/index/index.js

import wx from 'labrador';
import List from '../../components/list/list';
import Title from '../../components/title/title';

export default class Index extends wx.Component {
  data = {
    userInfo: {}
  };
  children = {
    list: new List(),
    motto: new Title({ text: 'Hello world' })
  };

  //事件处理函数
  handleViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  }

  async onLoad() {
    //调用应用实例的方法获取全局数据
    let userInfo = await wx.app.getUserInfo();
    //更新数据
    this.setData({
      userInfo: userInfo
    });
    this.update();
  }
}

layout src/pages/index/index.xml

<view class="container">
  <view bindtap="handleViewTap" class="userinfo">
    <image class="userinfo-avatar" src="{{ userInfo.avatarUrl }}" background-size="cover"/>
    <text class="userinfo-nickname">{{ userInfo.nickName }}</text>
  </view>
  <view class="usermotto">
    <component key="motto" name="title"/>
  </view>
  <component key="list"/>
</view>

style

@import 'list';
@import 'title';

.motto-title-text {
  font-size: 3em;
  padding-bottom: 1rem;
}

/* ... */

Format page code and custom components exactly the same format, our thinking is a page component is the only difference, pages, and custom components code page is stored in the pagesdirectory.

js logic code using the same exportstatement to export a default class, nor can we manually call the Page()method, because after compilation, pagesall js files in the directory will automatically call all Page()method declarations page.

We see that the component class, a property of the object children, the attribute defines the dependency of the component, other custom components contained in the above code contains two pages custom components listand title, the two custom components key, respectively, as listand motto.

xml layout code using the supplied Labrador <component/>label, this label is introduced into the role of a self-defined layout file subassembly tag has two attributes, namely key(mandatory), and name(optional, defaults to the value of key) . keyAnd component logic js code keycorresponding to, nameused src/componetsand node_moduleslooking subassembly template directory. Runtime, the class key sub-assembly corresponding to the logic code is datarendered to the sub-assembly template.

less style file, we used two @importstatements to load subassemblies style, here's @import 'list'statement in accordance with LESS syntax, it will first look in the current directory src/pages/index/in the list.lessfile, if no attempts to find src/componetsand node_modulescomponent-style directory.

Next, we define the .motto-title-textstyle, do so because mottothe template title of representative of the key components in a view belonging to the title-textclass, compile time, Labrador will automatically add a prefix for its motto-so class compiled this view belongs title-text motto-title-textthen we style code can be used in the parent component's .motto-title-textstyle redefined subassembly.

Note Although we have used LESS files, due to the limitations of the WeChat applet framework, we cannot use the level selection and nesting syntax of LESS. But we can use LESS variables, mixins, functions and other functions to facilitate development.

Further Labrador supports multiple nested assembly, in the example described above, indexcomprising a sub-assembly listand title, listcomprising a sub-assembly title, so that in the final display, indexback display page two titlecomponents.

See detailed code labrador initsample project generated commands.

to sum up

Pages are also components. All components have the same lifecycle functions onLoad, onReady, onShow, onHide, onUnload and setData.

componetsAnd pagestwo directories difference is that componetscomponents can be stored in smart loaded, pagesthe directory automatically add the components at compile time Page()to call, so the pagesdirectory components can not be called by other components if a component needs to be reused, store in the componetsdirectory NPM or packaged into packets.

Contributor

Zhengzhou Pulse Software Technology Co., Ltd.

Liang Xingchen

Open source agreement

This project is released under the MIT open source agreement, allowing any organization and individual to use it for free.

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12735732.html