微信小程序開發實戰——使用第三方庫Immutable.js
Immutable 是 非死book 開發的不可變數據集合。不可變數據一旦創建就不能被修改,是的應用開發更簡單,允許使用函數式編程技術,比如惰性評估。Immutable JS 提供一個惰性Sequence,允許高效的隊列方法鏈,類似 map 和 filter ,不用創建中間代表。immutable 通過惰性隊列和哈希映射提供 Sequence, Range, Repeat, Map, OrderedMap, Set 和一個稀疏 Vector。
微信小程序無法直接使用require( 'immutable.js' )進行調用,需要對下載的Immutable代碼進行修改,才能使用。
原因分析
Immutable使用了UMD模塊化規范
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Immutable = factory());
}(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice;
....
}));
UMD的實現很簡單,先判斷是否支持Node.js(CommonJS)模塊規范,存在則使用Node.js(CommonJS)方式加載模塊。再判斷是否支持AMD,存在則使用AMD方式加載模塊。前兩個都不存在,則將模塊公開到全局。
exports、module必須都有定義,才能以CommonJS加載模塊。通過測試,微信小程序運行環境exports、module并沒有定義。
解決方法
修改Immutable代碼,注釋原有模塊導出語句,使用module.exports = factory() 強制導出
(function(global, factory) {
/*
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Immutable = factory());
*/
module.exports = factory();
}(this, function() {
使用Immutable.js
//index.js
var Immutable = require( '../../libs/immutable/immutable.modified.js' );
//獲取應用實例
var app = getApp();
Page( {
onLoad: function() {
//console.log('onLoad');
var that = this;
var lines = [];
lines.push( "var map1 = Immutable.Map({a:1, b:2, c:3});" );
var map1 = Immutable.Map({a:1, b:2, c:3});
lines.push( "var map2 = map1.set('b', 50);" );
var map2 = map1.set('b', 50);
lines.push( "map1.get('b');" );
lines.push(map1.get('b'));
lines.push( "map2.get('b');" );
lines.push(map2.get('b'));
this.setData( {
text: lines.join( '\n' )
})
}
})
來自:https://segmentfault.com/a/1190000007016139
本文由用戶 zwb7926 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!