引入
方式一:npm安装
微信小程序支持npm包
npm i --save lodash
方式一:下载min.js压缩包
wget https://raw.githubusercontent.com/lodash/lodash/4.17.15-npm/lodash.min.js \ -O lodash@4.17.15.min.js
复制到libs文件夹
使用
// import _ from 'lodash'; import _ from './libs/lodash@4.17.15.min.js'; // 全局挂载lodash工具库 wx.$_ = _;
对比
npm此方式引入的包体积很大,占用了533KB,而微信单包体积允许2M
上传代码时,微信开发者工具并没有将lodash包进行打包压缩
所以采用min.js方式,以减少包体积
问题
引入lodash后,运行小程序会报错
需要引入一个修复包
lodash-fix.js
/** * 修复 微信小程序中lodash 的运行环境 */ global.Object = Object; global.Array = Array; // global.Buffer = Buffer global.DataView = DataView; global.Date = Date; global.Error = Error; global.Float32Array = Float32Array; global.Float64Array = Float64Array; global.Function = Function; global.Int8Array = Int8Array; global.Int16Array = Int16Array; global.Int32Array = Int32Array; global.Map = Map; global.Math = Math; global.Promise = Promise; global.RegExp = RegExp; global.Set = Set; global.String = String; global.Symbol = Symbol; global.TypeError = TypeError; global.Uint8Array = Uint8Array; global.Uint8ClampedArray = Uint8ClampedArray; global.Uint16Array = Uint16Array; global.Uint32Array = Uint32Array; global.WeakMap = WeakMap; global.clearTimeout = clearTimeout; global.isFinite = isFinite; global.parseInt = parseInt; global.setTimeout = setTimeout;
在引入lodash之前就引入修复包
import './libs/lodash-fix.js'; import _ from './libs/lodash@4.17.15.min.js';
参考
微信小程序引入 lodash