lodash-webpack-plugin插件
2026/5/16 4:49:01 网站建设 项目流程

进行webpack打包优化时,为了缩小lodash的打包体积使用了lodash-webpack-plugin插件,但是运行项目后页面报错Uncaught TypeError: predicate is not a function

解决方法:使用插件时开启对应的配置:(开启后包体积会相应增加)

shorthandsIteratee 是_.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”方法。
(需要currying

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的优化。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询