小程序給我們暴(bao)露了兩個參數 require 和 module , require 用(yong)來在(zai)模塊中加載其(qi)他模塊,module 用(yong)來將模塊中的方法暴(bao)露出(chu)去
module.exports = function(){}
所以(yi)只要需要讓第三方庫的代碼使用(yong)這種形(xing)式的 export 就可以(yi)了
打一個 Redux 包,讓它(ta)可以兼容微信小(xiao)城的加(jia)載方式
git clone //github.com/reactjs/redux.git npm install # 詳細內容可以到redux項目的package.json中查看 # 這些命令是是使用webpack構建UMD模式的包。也就是說所有的代碼,包括依賴的庫都會被打包到一個文件中,并且自帶一段模塊加載代碼,文件可以在dist目錄下找到 npm run build:umd && npm run build:umd
用(yong)編輯器(qi)打開 dist 目錄下的(de) redux.js 文件
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Redux"] = factory();
else
root["Redux"] = factory();
})(this, function() {
...
})
因為微信小程序的開發環境是定制的,暫(zan)時沒有發現辦法直接安裝 redux-devtool 的插件
npm install -g remotedev-server remotedev --hostname=localhost --port=5678
因(yin)為沒辦法用 npm 安(an)裝(zhuang)(zhuang)到(dao)本地(微信小程序(xu)會嘗(chang)試去加(jia)載(zai)項目目錄中的所(suo)有js),所(suo)以這(zhe)里使(shi)用全局安(an)裝(zhuang)(zhuang),第(di)二(er)條命令(ling)是啟動 remotedev-server , hostname 和 port 分(fen)別指定為 localhost和 5678
在 store 下集成(cheng) devtool
const {createStore, compose} = require('./libs/redux.js');
const devTools = require('./libs/remote-redux-devtools.js').default;
const reducer = require('./reducers/index.js')
function configureStore() {
return createStore(reducer, compose(devTools({
hostname: 'localhost',
port: 5678,
secure: false
})));
}
module.exports = configureStore;
把 devtool 使用 redux 的 compose 加(jia)到 store 中去。 hostname 和 port 是指(zhi)定(ding)為(wei)之前啟(qi)動 remotedev-server 啟(qi)動時候指(zhi)定(ding)的參數。保存之后重啟(qi)一(yi)下小程序,如(ru)果沒有報錯的話(hua)就OK了
Immutable 是 Facebook 開(kai)發(fa)的不可變數(shu)據集(ji)合。不可變數(shu)據一旦創建(jian)就(jiu)不能被修改,是的應(ying)用(yong)開(kai)發(fa)更簡單,允許使(shi)用(yong)函(han)數(shu)式編程(cheng)技術(shu),比(bi)如惰性評估。微信小程(cheng)序無法直接使(shi)用(yong) Immutable.js ,下(xia)面就(jiu)來說說微信小程(cheng)序如何(he)使(shi)用(yong)第三(san)方庫 Immutable.js
(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;
....
}));
修(xiu)改 Immutable 代(dai)碼,注(zhu)釋原有模塊導(dao)出語句,使用 module.exports = factory() 強(qiang)制導(dao)出
(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() {