ReactJS中uuid库默认导出错误问题求助
解决React项目中uuid库"does not contain a default export"错误
这个报错其实很好解决——问题出在uuid从v3版本开始就不再提供默认导出了,你写的import uuid from 'uuid'是针对v2及更早版本的写法,放到新版本里自然会报错。下面给你两种靠谱的解决方法,不会产生额外警告:
方法一:直接导入v4生成函数(官方推荐)
这是最规范的用法,不仅能解决报错,还能减少打包体积(只引入你需要的函数):
- 先确保你装的是最新版uuid:
npm install uuid # 用yarn的话 yarn add uuid
- 修改你的
alert.js代码:
import { v4 as uuidv4 } from 'uuid'; import { SET_ALERT, REMOVE_ALERT } from './types'; export const setAlert = (msg, alertType, timeout = 5000) => dispatch => { const id = uuidv4(); dispatch({ type: SET_ALERT, payload: { msg, alertType, id } }); setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout); };
这里把v4重命名为uuidv4是为了避免和其他变量名冲突,你也可以直接用import { v4 } from 'uuid',然后调用v4()生成ID。
方法二:导入整个uuid模块(兼容旧写法习惯)
如果你还是想用uuid.v4()的调用方式,可以用通配符导入整个模块,但这种方式会把uuid里所有生成器(比如v1、v3)都打包进来,不太推荐:
import * as uuid from 'uuid'; import { SET_ALERT, REMOVE_ALERT } from './types'; export const setAlert = (msg, alertType, timeout = 5000) => dispatch => { const id = uuid.v4(); dispatch({ type: SET_ALERT, payload: { msg, alertType, id } }); setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout); };
为什么之前的方案会产生警告?
很多人会尝试用require('uuid').v4这类CommonJS的写法,而React项目一般默认用ES模块规范,这就会触发ESLint的import/no-commonjs或者no-undef警告。上面两种方法都是纯ES模块的写法,完全符合React项目的规范,不会出现这类问题。
内容的提问来源于stack exchange,提问作者user7696478
相关产品推荐
相关产品推荐

