Detailed examples of modularization in WeChat development
JavaScriptModule Specification
Modularization is very common in any large application, unlike some more traditional programming languages. , JavaScript (ECMA-262 version) does not yet support native modularization.
The Javascript community has made a lot of efforts to achieve the effect of "module" in the existing running environment. There are two main popular JavaScript module specifications: CommonJS, AMD, UMD, CMD, etc.
CommonJS
CommonJS specification is a server-side Javascript module specification.
The module system of Node.js is implemented with reference to the CommonJS specification. NPM also follows the package specifications defined by commonJS, thus forming a complete ecosystem.
The modules defined by CommonJS are divided into: {Module reference (require)} {Module definition (exports)} {Module identification (module)}. require() is used to introduce external modules; the exports object is used to export methods or variables of the current module, the only export port; the module object represents the module itself.
CommonJS specification wiki.commonjs.org/wiki...
function MathClass() { } MathClass.PI = 3.14; MathClass.E = 2.72; MathClass.prototype.add = function(a, b) { return a+b; }; module.exports = MathClass;
var MathClass = require('./mathCommonJS.js'); Page( { onLoad: function() { console.log( "PI: " +MathClass.PI ); var mathClass = new MathClass(); console.log( "3 + 4: " +mathClass.add(3, 4) ); } });
AMD
AMD is the abbreviation of "Asynchronous Module Definition", which means "Asynchronous module definition" is a front-end module specification.
RequireJS implements the AMD specification.
AMD specification defines a free variable or global variable define function.
define( id?, dependencies?, factory );
id is a string type, which represents the module identification and is an optional parameter. If not present the module ID should default to the ID of the requested script in the loader. If present, the module identifier must be top-level or an absolute identifier.
dependencies is an array literal of module identifiers that the current module depends on and has been defined by the module.
factory is a function or object that needs to be instantiated.
AMD specification github.com/amdjs/amdj...
define('mathAMD', [], function( i ) { function MathClass() { } MathClass.PI = 3.14; MathClass.E = 2.72; MathClass.prototype.add = function( a, b ) { return a + b; }; return MathClass; });
define( [ "mathAMD" ], function( require, exports, MathClass ) { Page( { onLoad: function() { console.log( "PI: " + MathClass.PI ); var mathClass = new MathClass(); console.log( "3 + 4: " + mathClass.add( 3, 4 ) ); } }); });
UMD
CommonJS module is based on the server side The first principle of development is to choose to load modules synchronously. Its modules do not require packaging, but it only supports object type (objects) modules. AMD develops based on the browser-first principle and chooses to load modules asynchronously. Its module supports various types of modules such as objects, functions, constructors, strings, JSON, etc., so it is very flexible in the browser. This forces people to come up with another more general format, UMD (Universal Module Definition), hoping to provide a front-end and cross-platform solution.
(function (root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('jquery')); } else { root.returnExports = factory(root.jQuery); } }(this, function ($) { function myFunc(){}; return myFunc; }));
The implementation of UMD is very simple. First determine whether AMD is supported (whether define exists), and if it exists, use the AMD method to load the module. Then determine whether the Node.js module format is supported (whether exports exists). If it exists, use the Node.js module format. If the first two do not exist, the module will be exposed to the world (window or global).
( function( global, factory ) { if( typeof define === 'function' && define.amd ) { define( factory ); } else if( typeof exports === 'object' ) { module.exports = factory(); } else { root.returnExports = factory(); } } ( this, function() { function MathClass() { } MathClass.PI = 3.14; MathClass.E = 2.72; MathClass.prototype.add = function( a, b ) { return a + b; }; return MathClass; }) );
var MathClass = require( './mathUMD.js' ); Page( { onLoad: function() { console.log( "PI: " + MathClass.PI ); var mathClass = new MathClass(); console.log( "3 + 4: " + mathClass.add( 3, 4 ) ); } });
CMD
CMD 即Common Module Definition通用模块定义,CMD规范是国内发展出来的,就像AMD有个requireJS,CMD有个浏览器的实现SeaJS,SeaJS要解 决的问题和requireJS一样,只不过在模块定义方式和模块加载(可以说运行、解析)时机上有所不同。
Sea.js 推崇一个模块一个文件,遵循统一的写法
define(id?, deps?, factory)
因为CMD推崇一个文件一个模块,所以经常就用文件名作为模块id,CMD推崇依赖就近,所以一般不在define的参数中写依赖,在factory中写。
factory是一个函数,有三个参数,function(require, exports, module)
require 是一个方法,接受 模块标识 作为唯一参数,用来获取其他模块提供的接口
exports 是一个对象,用来向外提供模块接口
module 是一个对象,上面存储了与当前模块相关联的一些属性和方法
CMD模块规范 https://github.com/cmdjs/spec...
define( "pages/module/mathCMD.js", function( require, exports, module ) { function MathClass() { } MathClass.PI = 3.14; MathClass.E = 2.72; MathClass.prototype.add = function( a, b ) { return a + b; }; module.exports = MathClass; })
define( "pages/module/mathCMD.js", function( require, exports, module ) { function MathClass() { } MathClass.PI = 3.14; MathClass.E = 2.72; MathClass.prototype.add = function( a, b ) { return a + b; }; module.exports = MathClass; })
微信小程序模块化机制
微信小程序秉承了JavaScript模块化的机制,通过module.exports暴露对象,通过require来获取对象。
模块开发
以微信小程序QuickStart为例,微信小程序模块采用CommonJS规范
utils/util.js
function formatTime(date) { var year = date.getFullYear() var month = date.getMonth() + 1 var day = date.getDate() var hour = date.getHours() var minute = date.getMinutes() var second = date.getSeconds(); 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 } module.exports = { formatTime: formatTime }
pages/log/log.js
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)) }) }) } })
模块运行
微信小程序还是要以前端程序方式在微信浏览器中运行,由于CommonJS规范是服务器端模块规范,微信小程序运行时会自动转换为前端模块规范。
以微信小程序QuickStart调试时代码为例
utils/util.js
define("utils/util.js", function(require, module) { var window = { Math: Math }/*兼容babel*/ , location, document, navigator, self, localStorage, history, Caches; function formatTime(date) { var year = date.getFullYear() var month = date.getMonth() + 1 var day = date.getDate() var hour = date.getHours() var minute = date.getMinutes() var second = date.getSeconds(); 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 } module.exports = { formatTime: formatTime } })
pages/log/log.js
define("pages/logs/logs.js", function(require, module) { var window = { Math: Math }/*兼容babel*/ , location, document, navigator, self, localStorage, history, Caches; 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)) }) }) } }) }); require("pages/logs/logs.js")
微信小程序运行的代码与CMD模块规范基本符合。
使用第三方模块
微信小程序运行环境exports、module没有定义,无法通过require导入模块,需要对第三方模块强制导出后才能正常导入。
微信小程序使用Immutable.js segmentfault.com/a/11...
微信小程序使用Underscore.js segmentfault.com/a/11...
ECMAScript 6模块系统
ECMAScript 6,模块被作为重要组成部分加入其中。
ES6的模块提供了2个新的语法,分别是export和import。
export 模块导出
export let a = 1; export class A {}; export let b = () => {};
import 模块导入
import {a} from './a'; console.log(a); import * as obj from './a'; console.log(obj.a);
微信小程序还没实现ECMAScript 6。
【相关推荐】
1. 微信公众号平台源码下载
3. 微信开发之微信支付
The above is the detailed content of Detailed examples of modularization in WeChat development. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to Optimize the Maintainability of Java Code: Experience and Advice In the software development process, writing code with good maintainability is crucial. Maintainability means that code can be easily understood, modified, and extended without causing unexpected problems or additional effort. For Java developers, how to optimize the maintainability of code is an important issue. This article will share some experiences and suggestions to help Java developers improve the maintainability of their code. Following standardized naming rules can make the code more readable.

Python is a simple, easy-to-learn and efficient programming language, but when we write Python code, we may encounter some problems with excessive code complexity. If these problems are not solved, it will make the code difficult to maintain, error-prone, and reduce the readability and scalability of the code. So, in this article, we will discuss how to resolve code complexity error in Python code. Understanding Code Complexity Code complexity is a measure of the nature of code that is difficult to understand and maintain. In Python, there are some indicators that can be used

Python, as a high-level programming language, is widely used in software development. Although Python has many advantages, a problem that many Python programmers often face is that the maintainability of the code is poor. The maintainability of Python code includes the legibility, scalability, and reusability of the code. In this article, we will focus on how to solve the problem of poor maintainability of Python code. 1. Code readability Code readability refers to the readability of the code, which is the core of code maintainability.

In modern web development, Vue, as a flexible, easy-to-use and powerful front-end framework, is widely used in the development of various websites and applications. When developing large-scale projects, how to simplify the complexity of the code and make the project easier to maintain is a problem that every developer must face. Modular development can help us better organize code, improve development efficiency and code readability. Below, I will share some experiences and guidelines for implementing modular development in Vue large-scale projects: 1. Clear division of labor in a large-scale project

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

In Vue, modularization is to encapsulate a single function into a module (file). The modules are isolated from each other, but internal members can be exposed through specific interfaces, and they can also rely on other modules (to facilitate code reuse, thus Improve development efficiency and facilitate later maintenance). The benefits of modular development: 1. Clear organization and easy maintenance; 2. All data will not be requested back at once, and the user experience is good; 3. Modules are isolated from each other, but internal members can be exposed through specific interfaces, or Depends on other modules.

As a high-level programming language, Python is widely used in data analysis, machine learning, web development and other fields. However, as the size of the code continues to expand, the scalability problem of Python programs gradually becomes apparent. Poor scalability error means that the Python program cannot adapt well to changes in requirements under certain circumstances and cannot process large-scale data, resulting in poor program performance. Too many dependencies, poor code structure, lack of documentation, etc. are all culprits of poor scalability errors in Python programs.

According to news from this website on August 14, Chaoen Vecow launched the TGS-1000 series industrial mini host equipped with the first generation Intel Core Ultra processor on July 22, Beijing time. The special feature of this series of products is that it supports vertical stacking to expand additional I/O ports. The TGS-1000 series is divided into two models: TGS-1000 and TGS-1500. The difference is that the bottom of the TGS-1500 contains a module that supports MXM graphics cards. It can choose Intel Ruixuan A370M or up to RTX5000Ada mobile version of Nvidia professional cards. ▲TGS-1500TGS-1000 series mini hosts are available with Intel Core Ultra7165H or Ultra5135H processors, equipped with dual D
