微信小程序開發實戰——模塊化

dondon961 8年前發布 | 28K 次閱讀 微信小程序開發 移動開發

JavaScript模塊規范

在任何一個大型應用中模塊化是很常見的,與一些更傳統的編程語言不同的是,JavaScript (ECMA-262版本)還不支持原生的模塊化。

Javascript社區做了很多努力,在現有的運行環境中,實現"模塊"的效果。通行的JavaScript模塊規范主要有兩種:CommonJS、AMD、UMD、CMD等

CommonJS

CommonJS規范是服務器端Javascript模塊規范。

Node.js的模塊系統,就是參照CommonJS規范實現的。NPM也遵循了commonJS定義的包規范,從而形成了一套完整的生態系統。

CommonJS定義的模塊分為:{模塊引用(require)} {模塊定義(exports)} {模塊標識(module)}。require()用來引入外部模塊;exports對象用于導出當前模塊的方法或變量,唯一的導出口;module對象就代表模塊本身。

CommonJS規范 http://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是"Asynchronous Module Definition"的縮寫,意思是"異步模塊定義",是前端模塊規范。

RequireJS就是實現了AMD規范的呢。

AMD規范定義了一個自由變量或者說是全局變量 define 的函數。

define( id?, dependencies?, factory );
  • id 為字符串類型,表示了模塊標識,為可選參數。若不存在則模塊標識應該默認定義為在加載器中被請求腳本的標識。如果存在,那么模塊標識必須為頂層的或者一個絕對的標識。

  • dependencies ,是一個當前模塊依賴的,已被模塊定義的模塊標識的數組字面量。

  • factory,是一個需要進行實例化的函數或者一個對象。

AMD規范 https://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 ) );
        }
    });

});</code></pre>

UMD

CommonJS module以服務器端為第一的原則發展,選擇同步加載模塊。它的模塊是無需包裝的,但它僅支持對象類型(objects)模塊。AMD以瀏覽器為第一(browser-first)的原則發展,選擇異步加載模塊。它的模塊支持對象、函數、構造器、字符串、JSON等各種類型的模塊,因此在瀏覽器中它非常靈活。這迫使人們想出另一種更通用格式 UMD(Universal Module Definition),希望提供一個前后端跨平臺的解決方案。

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

UMD的實現很簡單,先判斷是否支持AMD(define是否存在),存在則使用AMD方式加載模塊。再判斷是否支持Node.js模塊格式(exports是否存在),存在則使用Node.js模塊格式。前兩個都不存在,則將模塊公開到全局(window或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; }) );</code></pre>

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 }</code></pre>

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 https://segmentfault.com/a/11...

微信小程序使用Underscore.js https://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);</code></pre>

微信小程序還沒實現ECMAScript 6。

 

 

來自:https://segmentfault.com/a/1190000007028276

 

 本文由用戶 dondon961 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!