小程序給我們暴露了兩個參數(shù) require 和 module , require 用來在模塊中加載其他模塊,module 用來將模塊中的方法暴露出去
module.exports = function(){}
所以只要需要讓第三方庫的代碼使用這種形式的 export 就可以了
打一個 Redux 包,讓它可以兼容微信小城的加載方式
git clone https://github.com/reactjs/redux.git npm install # 詳細(xì)內(nèi)容可以到redux項目的package.json中查看 # 這些命令是是使用webpack構(gòu)建UMD模式的包。也就是說所有的代碼,包括依賴的庫都會被打包到一個文件中,并且自帶一段模塊加載代碼,文件可以在dist目錄下找到 npm run build:umd && npm run build:umd
用編輯器打開 dist 目錄下的 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() {
...
})
因為微信小程序的開發(fā)環(huán)境是定制的,暫時沒有發(fā)現(xiàn)辦法直接安裝 redux-devtool 的插件
npm install -g remotedev-server remotedev --hostname=localhost --port=5678
因為沒辦法用 npm 安裝到本地(微信小程序會嘗試去加載項目目錄中的所有js),所以這里使用全局安裝,第二條命令是啟動 remotedev-server , hostname 和 port 分別指定為 localhost和 5678
在 store 下集成 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 加到 store 中去。 hostname 和 port 是指定為之前啟動 remotedev-server 啟動時候指定的參數(shù)。保存之后重啟一下小程序,如果沒有報錯的話就OK了
Immutable 是 Facebook 開發(fā)的不可變數(shù)據(jù)集合。不可變數(shù)據(jù)一旦創(chuàng)建就不能被修改,是的應(yīng)用開發(fā)更簡單,允許使用函數(shù)式編程技術(shù),比如惰性評估。微信小程序無法直接使用 Immutable.js ,下面就來說說微信小程序如何使用第三方庫 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;
....
}));
修改 Immutable 代碼,注釋原有模塊導(dǎo)出語句,使用 module.exports = factory() 強制導(dǎo)出
(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() {