Heim  >  Artikel  >  WeChat-Applet  >  Detaillierte Beispiele der Modularisierung in der WeChat-Entwicklung

Detaillierte Beispiele der Modularisierung in der WeChat-Entwicklung

零下一度
零下一度Original
2017-05-31 16:26:551771Durchsuche

JavaScriptModulspezifikation

Im Gegensatz zu einigen traditionelleren Programmiersprachen, JavaScript (ECMA-262-Version), ist die Modularisierung in jeder großen Anwendung üblich. unterstützt noch keine native Modularisierung.

Die Javascript-Community hat große Anstrengungen unternommen, um den Effekt von „Modulen“ in der vorhandenen Betriebsumgebung zu erzielen. Es gibt zwei Haupttypen beliebter JavaScript-Modulspezifikationen: CommonJS, AMD, UMD, CMD usw.

CommonJS

Die CommonJS-Spezifikation ist eine serverseitige Javascript-Modulspezifikation .

Das Modulsystem von Node.js wird unter Bezugnahme auf die CommonJS-Spezifikation implementiert. NPM folgt auch den von commonJS definierten Paketspezifikationen und bildet so ein vollständiges Ökosystem.

Von CommonJS definierte Module sind unterteilt in: {Modulreferenz (erforderlich)} {Moduldefinition (Exporte)} {Modulidentifikation (Modul)}. require() wird zum Einführen externer Module verwendet. Das Exportobjekt wird zum Exportieren von Methoden oder Variablen des aktuellen Moduls verwendet. Der einzige Exportport repräsentiert das Modul selbst.

CommonJS-Spezifikation 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 ist „Asynchronous Module Definition“ Die Abkürzung „asynchrone Moduldefinition“ bedeutet „asynchrone Moduldefinition“ und ist eine Front-End-Modulspezifikation.

RequireJS implementiert die AMD-Spezifikation.

Die AMD-Spezifikation definiert eine freie Variable oder eine globale Variablendefinitionsfunktion.

define( id?, dependencies?, factory );
  • id ist ein String-Typ, der die Modul-ID darstellt und ein optionaler Parameter ist. Wenn nicht vorhanden, sollte die Modul-ID standardmäßig die ID des angeforderten Skripts im Loader sein. Falls vorhanden, muss der Modulbezeichner ein Top-Level- oder ein absoluter Bezeichner sein.

  • Abhängigkeiten sind ein Array-Literal, von dem das aktuelle Modul abhängt und das durch das vom Modul definierte Modul identifiziert wird.

  • Factory ist eine Funktion oder ein Objekt, das instanziiert werden muss.

AMD-Spezifikation 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 Das Modul wird nach dem Server-Side-First-Prinzip entwickelt und lädt Module synchron. Für seine Module ist keine Verpackung erforderlich, es werden jedoch nur Module vom Typ Objekt (Objekts) unterstützt. AMD entwickelt nach dem Browser-First-Prinzip und lädt Module asynchron. Sein Modul unterstützt verschiedene Arten von Modulen wie Objekte, Funktionen, Konstruktoren, Strings, JSON usw. und ist daher im Browser sehr flexibel. Dies zwingt die Leute dazu, ein anderes, allgemeineres Format zu entwickeln, UMD (Universal Module Definition), in der Hoffnung, eine Front-End- und plattformübergreifende Lösung bereitzustellen.

(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;
}));

Die Implementierung von UMD ist sehr einfach. Stellen Sie zunächst fest, ob AMD unterstützt wird (ob eine Definition vorhanden ist), und verwenden Sie, falls vorhanden, die AMD-Methode, um das Modul zu laden. Stellen Sie dann fest, ob das Node.js-Modulformat unterstützt wird (ob Exporte vorhanden sind), verwenden Sie das Node.js-Modulformat. Wenn die ersten beiden nicht vorhanden sind, wird das Modul der Welt (Fenster oder global) ausgesetzt.

( 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. 微信公众号平台源码下载

2. 分享微信公众号开发刷卡支付的实例教程

3. 微信开发之微信支付

4. 详解微信小程序支付功能开发错误总结

Das obige ist der detaillierte Inhalt vonDetaillierte Beispiele der Modularisierung in der WeChat-Entwicklung. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn