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 dist
the destination directory.
Development Process
Sublime waiting WebStorm or edit IDE src
directory of source code, and then run in the project root directory in labrador build
order 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 build
command updates the entiredist
directory, 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 watch
command to monitor src
the code directory, automatically builds when changes without editing code after every run manually labrador build
.
So the best posture is:
Run in the project
labrador watch
Coding in WebStorm, save
Switch to the micro channel web developer tools debugging, preview
Back to coding in WebStorm
...
labrador library
labrador
Library of global wx
variables package, most of the wx
methods were the object Promise support, in addition to on*
the beginning or at *Sync
the end of the method. Use the following code in labrador
the library.
import wx from 'labrador';
We do not recommend re-use wx.getStorageSync()
such as synchronous blocking method, and in the async
use 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 export
grammar 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/compontents
a directory, a file composed of three general components, *.js
, *.xml
and *.less
respectively correspond to the micro channel small framework js
, wxml
and wxss
files. In Labardor source project, we deliberately adopted xml
and less
suffix 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 export
syntax derived a default class that needs to inherit and labrador.Component
assembly base class.
Note component incident response methods must
handle
begin with! For example, abovehandleTap
page
We require that all pages must be stored in pages
the directory, subdirectory for each page of the file format and custom components consistent, but may be more of a *.json
configuration 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 pages
directory.
js logic code using the same export
statement to export a default class, nor can we manually call the Page()
method, because after compilation, pages
all 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 list
and title
, the two custom components key
, respectively, as list
and 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) . key
And component logic js code key
corresponding to, name
used src/componets
and node_modules
looking subassembly template directory. Runtime, the class key sub-assembly corresponding to the logic code is data
rendered to the sub-assembly template.
less style file, we used two @import
statements 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.less
file, if no attempts to find src/componets
and node_modules
component-style directory.
Next, we define the .motto-title-text
style, do so because motto
the template title of representative of the key components in a view belonging to the title-text
class, compile time, Labrador will automatically add a prefix for its motto-
so class compiled this view belongs title-text motto-title-text
then we style code can be used in the parent component's .motto-title-text
style 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, index
comprising a sub-assembly list
and title
, list
comprising a sub-assembly title
, so that in the final display, index
back display page two title
components.
See detailed code labrador init
sample project generated commands.
to sum up
Pages are also components. All components have the same lifecycle functions onLoad, onReady, onShow, onHide, onUnload and setData.
componets
And pages
two directories difference is that componets
components can be stored in smart loaded, pages
the directory automatically add the components at compile time Page()
to call, so the pages
directory components can not be called by other components if a component needs to be reused, store in the componets
directory NPM or packaged into packets.
Contributor
Zhengzhou Pulse Software Technology Co., Ltd.
Open source agreement
This project is released under the MIT open source agreement, allowing any organization and individual to use it for free.