← 中文资源

简体中文版本

Bun 模块已安装却未找到

Bun 无法解析已列在 package.json 且存在于 node_modules 的模块,通常因解析策略或条件导出。

阅读英文原文

症状分析

Bun 无法解析已列在 package.json 且存在于 node_modules 的模块,通常因解析策略或条件导出。 该错误在生产环境中出现,但可能不会在本地开发中复现,因为触发条件依赖于部署环境或运行时配置。理解完整的症状集合有助于将此问题与类似错误区分开来。

诊断实践

按照前置事项中的诊断步骤定位原因。每个步骤包含命令和输出解读。目标是缩小问题范围:配置、运行时还是应用代码。在最小化环境中复现错误后再应用修复。

根因

Bun uses a different module resolution algorithm than Node.js; packages with conditional exports or non-standard subpaths may not resolve under Bun stricter rules.

修复

Import only from the package main entry or a subpath explicitly listed in exports; if the package lacks an exports map, use the full path or open an issue with the package author. 应用修复后,监控系统以确认错误在负载下或不同环境中不再复现。

验证

Run the script with bun and confirm the module loads without error, then verify the imported function works as expected. 如果验证通过,修复即确认;如果未通过,重新检查诊断步骤中是否遗漏了促成因素。

诊断命令

运行以下命令复现和诊断问题:

bun pm ls | grep module-name
cat node_modules/module-name/package.json | grep -A20 exports
rm -rf node_modules/.cache && bun install