如何解决Lodash配置导入报错问题?
解决Lodash ES模块导入错误的方法
问题重现
安装Lodash后尝试两种导入方式均报错:
- 使用
import * as _ from './node_modules/lodash/lodash.js';时,报错:Uncaught TypeError: _.last is not a function - 使用
import _ from './node_modules/lodash/lodash.js';时,报错:Uncaught SyntaxError: The requested module './node_modules/lodash/lodash.js' does not provide an export named 'default'
解决方案
方案1:使用专门的ES模块版本lodash-es
Lodash官方提供了适配ES模块的包lodash-es,直接使用它可避免导入兼容问题:
- 安装
lodash-es:
npm install lodash-es
- 在代码中导入默认导出:
import _ from 'lodash-es'; const myListTest = ['water', 'apple']; const myNewArray = _.last(myListTest); console.log(myNewArray); // 输出 'apple'
方案2:兼容原lodash包的导入方式
如果不想更换包,可以通过获取模块的default属性来正确导入Lodash:
// 方式1:先导入模块对象,再取default import lodash from './node_modules/lodash/lodash.js'; const _ = lodash.default; const myListTest = ['water', 'apple']; const myNewArray = _.last(myListTest); console.log(myNewArray);
或者用动态导入的方式:
(async () => { const { default: _ } = await import('./node_modules/lodash/lodash.js'); const myListTest = ['water', 'apple']; const myNewArray = _.last(myListTest); console.log(myNewArray); })();
报错原因解释
import * as _报错:原lodash包的主文件是CommonJS格式,在ES模块环境下导入时,所有导出内容会被包裹在default属性中,而非直接挂载到导入的对象上,因此_.last无法找到对应函数。- 默认导入报错:CommonJS模块没有ES模块的
default导出标识,直接使用import _ from ...会被ES模块解析器认为缺少默认导出,从而抛出错误。
内容的提问来源于stack exchange,提问作者Metronidazol13
相关产品推荐
相关产品推荐

