进行webpack打包优化时,为了缩小lodash的打包体积使用了lodash-webpack-plugin插件,但是运行项目后页面报错 Uncaught TypeError: predicate is not a function
解决方法:使用插件时开启对应的配置:(开启后包体积会相应增加)
shorthands | Iteratee 是_.property , _.matches , &的简写形式_.matchesProperty 。 |
cloning | 支持“克隆”方法和克隆源对象。 |
currying | 支持“咖喱”方法。 |
caching | 缓存诸如_.cloneDeep , _.isEqual , & 之类的方法_.uniq 。 |
collections | 支持“Collection”方法中的对象。 |
exotics | 支持缓冲区、映射、集合、符号、类型化数组等对象。 |
guards | 主机对象、稀疏数组和其他边缘情况的防护。 |
metadata | 用于减少绑定、柯里化和部分应用函数包装的元数据。 (需要 currying ) |
deburring | 支持字母去毛刺。 |
unicode | 支持 Unicode 符号。 |
chaining | 支持链序列的组件。 |
memoizing | 支持_.memoize 和记忆。 |
coercions | 支持将值强制转换为整数、数字和字符串。 |
flattening | 支持“展平”方法和展平其余参数。 |
paths | 对_.get , _.has , & 等方法的深度属性路径支持_.set 。 |
placeholders | 参数占位符支持“bind”、“curry”和“partial”方法。 |
1. Uncaught TypeError: predicate is not a function :
'shorthands': true, 'collections': true,
2. Uncaught TypeError: Cannot read properties of undefined (reading 'length')
'flattening': true,
记录一下使用lodash-webpack-plugin插件
使⽤ babel-plugin-lodash 和 lodash-webpack-plugin:
babel-plugin-lodash: 对代码中的 import _ from 'lodash'或者import { add } from 'lodash/fp'进⾏编译优化。确保引⼊最⼩的包。
lodash-webpack-plugin:⽤于精简lodash,去除了⼀些特性,如果需要⽤到,则需⼿动开启。
配置方式如下:
安装babel-plugin-lodash后配置:
extraBabelPlugins: [
['lodash'],
],
lodash-webpack-plugin配置为:
import lodashModuleReplacementPlugin from 'lodash-webpack-plugin';
chainWebpack(config, { webpack }) {
//优化lodash
config.plugin("loadshReplace").use(new LodashModuleReplacementPlugin({
// 'caching': true,
// 'chaining': true,
// 'currying': true,
// 'cloning': true,
// 'coercions': true,
// 'collections': true,
// 'deburring': true,
// 'exotics': true,
// 'flattening': true,
// 'guards': true,
// 'memoizing': true,
// 'metadata': true,
// 'paths': true,
// 'placeholders': true,
// 'shorthands': true,
// 'unicode': true,
}));
},
注:lodash优化效果有限:随着系统的增⻓,引⼊的第三⽅库越来越多。⽽第三⽅库中,有可能使⽤require('lodash')引⼊lodash,导致我们项⽬中对lodash的优化⽆效。所以,可以不⽤太过于纠结lodash的优化。