使用Node 14.0与Webpack打包时Lodash报错:无法读取undefined的‘has’属性
解决Node 14 + Webpack导入Lodash报
cannot read 'has' of undefined的方案 1. 先检查导入方式
别用不规范的导入写法,比如import _ from 'lodash/has'这种肯定出错。按需导入就写import has from 'lodash/has'或者import { has } from 'lodash';要是全量导入,确认安装的是Lodash 4.x版本——Node14对这个版本兼容没问题。
2. 排查Webpack配置问题
- 要是Webpack对Lodash的解析出问题,试试在
webpack.config.js里加别名配置:const path = require('path'); module.exports = { resolve: { alias: { 'lodash$': 'lodash', 'lodash/has': path.resolve(__dirname, 'node_modules/lodash/has.js') } } }; - 要是用了
babel-plugin-lodash,得确保Babel配置正确,版本也匹配。.babelrc里这么写:
别忘了装依赖:{ "plugins": ["lodash"] }npm install babel-plugin-lodash --save-dev
3. 清依赖重装试试
删掉node_modules和package-lock.json,然后重新安装:
rm -rf node_modules package-lock.json npm install
直接指定Lodash稳定版本更稳妥:npm install lodash@4.17.21
4. 检查Node模块兼容问题
Node14对ES模块支持有限,别混用CommonJS和ES模块导入。比如Webpack的output.libraryTarget设成commonjs2的话,导入方式得对应上。
5. 排查代码变量冲突
检查项目里是不是把_这个变量重新赋值成undefined了——比如某个地方写了_ = undefined,那调用_.has肯定报错。在报错位置附近打个console.log(_)看看变量值就清楚了。
内容的提问来源于stack exchange,提问作者Colton Neifert
相关产品推荐
相关产品推荐

