WeChat Mini Program Development - Modular
JavaScript Modular Reference Documentation
|
JS Modular
WeChat Mini Program adheres to the JavaScript modularization mechanism, extracts some public code into a separate js file as a module, exposes objects through module.exports or exports, and obtains objects through require.
have to be aware of is:
|
Take the modular processing time in the util.js file as an example:
/** * Handle specific business logic */ function formatTime(date) { //get year month day var year = date.getFullYear() var month = date.getMonth() + 1 var day = date.getDate() // get the hours, minutes and seconds var hour = date.getHours() var minute = date.getMinutes() var second = date.getSeconds(); // format the date return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':') } function formatNumber(n) { n = n.toString() return n[1] ? n : '0' + n } /** * Modular export exposed interface */ module.exports = { formatTime: formatTime }
How to use:
// import the modular approach var util = require ('../../ utils / util.js') Page({ data: { logs: [] }, onLoad: function () { this.setData({ logs: (wx.getStorageSync('logs') || []).map(function (log) { return util.formatTime(new Date(log)) }) }) } })
WXML Modular
The wxml code can also be divided into blocks according to different parts of the interface. The files separated from the main wxml file can be written as a template template, or another piece of wxml code, which can be imported through import or include to achieve modularization. |
WXSS Modular
wxss also supports modularization, use @import to import other wxss files into the main wxss file (to be placed at the top of the main wxss file). Such as: @ import "base.wxss" ; |
A few tips for modularization
1. Extract the modules shared by js and put them in a folder, named as common , which can be divided into finer modules by function, such as network request module common/net.js , tool method set common/util. js , websocket related modules, etc.
2. Put the shared header and bottom of the page into page/common/ , remember to put js and wxml together.
3. If you refer to external libraries, put their files in the lib/ directory.
4. The directory division of pages and files mentioned in the previous article does not need to be changed. For example , the page/ directory is dedicated to storing pages, and a pair of names ( xxx.wxml and xxx.js ) corresponds to a page. If it is only a part of the page, it can be placed in the page/[page_name]/ directory to indicate the module dedicated to this page. , but if it is shared by several pages, it can be placed in the page/common/ mentioned in point 2 above
5. The template is placed in the tpl/ directory, and divided into folders according to the page.
6. If the related event handler has a lot of logic, it can be extracted separately and put into a file. |