Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Modularization of Wechat Development

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the modularization of Wechat development example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

JavaScript module specification

Modularity is common in any large application, and unlike some of the more traditional programming languages, JavaScript (ECMA-262 version) does not support native modularity.

The Javascript community has made a lot of efforts to achieve the effect of "modules" in the existing operating environment. There are two main JavaScript module specifications: CommonJS, AMD, UMD, CMD and so on.

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 specification 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 the methods or variables of the current module, the only exit; and the module object represents the module itself.

CommonJS specification wiki.commonjs.org/wiki...

Function MathClass () {} MathClass.PI = 3.14 function Class.prototype.add = function (a, b) {MathClass.prototype.add; 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" and is the front-end module specification.

RequireJS implements the AMD specification.

The AMD specification defines a function of a free variable or global variable define.

Define (id?, dependencies?, factory)

Id is a string type that represents the module identity and is an optional parameter. If it does not exist, the module identity should be defined by default as the identity of the requested script in the loader. If it exists, the module identity must be top-level or an absolute identity.

Dependencies is the literal amount of an array that the current module depends on and has been identified by the module defined by the module.

Factory is a function or an 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 develops according to the principle that the server side is the first, and chooses synchronous loading module. Its modules do not need to be wrapped, but it only supports object type (objects) modules. AMD develops according to the principle that browser is the first (browser-first) and chooses asynchronous loading module. Its modules support various types of modules, such as objects, functions, constructors, strings, JSON, and so on, so it is very flexible in browsers. This forces people to come up with another more general format, UMD (Universal Module Definition), which wants to provide a front and back end 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 to support AMD (whether define exists or not), and then use AMD to load the module. Then determine whether the Node.js module format is supported (whether exports exists), and if it exists, the Node.js module format is used. If neither of the first two exists, expose the module to the global (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 is the general module definition of Common Module Definition. The CMD specification is developed domestically, just like AMD has a requireJS,CMD and a browser. SeaJS,SeaJS has the same problem to solve as requireJS, but it is different in the mode of module definition and the timing of module loading (that is, running and parsing).

Sea.js advocates one module and one file, following a unified way of writing.

Define (id?, deps?, factory)

Because CMD favors one file per module, it often uses the file name as the module id,CMD recommends dependency proximity, so it generally does not write dependencies in the parameters of define, but in factory.

Factory is a function with three arguments, function (require, exports, module)

Require is a method that accepts the module ID as the only parameter to get the interface provided by other modules

Exports is an object that provides module interfaces to the outside world.

Module is an object that stores some properties and methods associated with the current module

CMD module specification 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;}) WeChat Mini Programs modularization mechanism

WeChat Mini Programs adheres to the modular mechanism of JavaScript, exposing objects through module.exports and obtaining objects through require.

Module development

Take WeChat Mini Programs QuickStart as an example, WeChat Mini Programs module adopts CommonJS specification

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))})}) module runs

WeChat Mini Programs still has to run in Wechat browser as a front-end program. Because the CommonJS specification is a server-side module specification, WeChat Mini Programs will automatically convert it to the front-end module specification at runtime.

Take WeChat Mini Programs QuickStart debugging time code as an example

Utils/util.js

Define ("utils/util.js", function (require, module) {var window = {Math: Math} / * compatible with 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} / * compatible with 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")

The code run by WeChat Mini Programs is basically consistent with the CMD module specification.

Use a third-party module

WeChat Mini Programs's running environment exports and module are not defined, so modules cannot be imported through require. Third-party modules need to be forcibly exported before they can be imported normally.

WeChat Mini Programs uses Immutable.js segmentfault.com/a/11...

WeChat Mini Programs uses Underscore.js segmentfault.com/a/11...

ECMAScript 6 module system

ECMAScript 6, the module is added as an important part.

ES6's module provides two new grammars, export and import.

Export module export

Export let a = 1; export class A {}; export let b = () = > {}

Import module import

Import {a} from'. / obj.a; console.log (a); import * as obj from'. / averse; console.log (obj.a)

WeChat Mini Programs has not implemented ECMAScript 6 yet.

Thank you for reading this article carefully. I hope the article "Modularization example Analysis of Wechat Development" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. more related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report