TypeScript+Rollup使用uuid时出现“Cannot read properties of undefined (reading 'v4')”错误
问题根源
出现Cannot read properties of undefined (reading 'v4')的核心原因有两点:
- Rollup配置中将
uuid标记为external,打包时会跳过该模块,但浏览器环境没有内置uuid模块,运行时无法找到对应导出。 @rollup/plugin-replace全局替换了require为空函数,而uuid内部依赖require加载子模块,导致其无法正常初始化。
解决方案
1. 移除external中的uuid配置
浏览器不支持Node.js模块解析机制,必须将uuid打包进最终bundle才能运行。打开rollup.config.js,删除external: ["uuid"]这一行:
export default [ { input: "src/index.ts", output: { file: "dist/bundle.js", format: "cjs", }, // 移除 external: ["uuid"] plugins: [ // ... 其他插件 ], }, ];
2. 调整或移除replace插件配置
全局替换require会破坏所有依赖该方法的模块。如果没有特殊需求,直接移除该插件配置:
// 删掉这段配置 replace({ require: "function(){}", preventAssignment: true, }),
若确实需要替换特定场景的require,请缩小替换范围,比如只替换自定义占位符而非全局require。
3. 优化Rollup插件顺序
插件执行顺序会影响模块处理结果,建议将typescript放在nodeResolve和commonjs之后,确保先完成模块解析、CommonJS转ES模块,再处理TypeScript编译:
plugins: [ image(), terser(), postcss(), nodeResolve(), commonjs(), builtins(), typescript({ tsconfig: "tsconfig.json", }), json(), // 已移除replace插件 ],
4. 可选:直接使用浏览器专用UUID入口
如果上述调整仍有问题,可直接导入uuid的浏览器ESM版本,绕开模块解析问题:
import { v4 as uuidv4 } from 'uuid/dist/esm-browser/v4.js';
验证修改
完成调整后重新执行Rollup打包命令,在浏览器中测试Web组件,uuidv4()即可正常生成唯一ID。
内容的提问来源于stack exchange,提问作者Mito toto
相关产品推荐
相关产品推荐

