Home >WeChat Applet >WeChat Development >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 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 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 ) ); } }); });
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 即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,模块被作为重要组成部分加入其中。
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!