bun 不是 npm 替代品,而是集运行时、包管理、测试、打包于一体的全栈工具链;它兼容 node.js 代码但需通过 code . 启动 vscode 并配置 pwa-node 调试及 tasks.json 测试任务才能正确集成。

Bun 不能直接替代 npm 运行 Node.js 项目 —— 它是独立运行时,不兼容 npm 的生命周期脚本(如 npm start),但可完全替代 node 和 npx 执行 JS/TS 文件、测试、构建等任务。关键不是“替换 npm”,而是让 VSCode 正确识别并调用 bun。
VSCode 终端找不到 bun 命令怎么办
根本原因是 VSCode 终端没加载系统 shell 的 PATH,尤其 macOS/Linux(zsh/fish)或 Windows(PowerShell)下,bun 安装路径(如 /opt/homebrew/bin/bun 或 $HOME/.bun/bin/bun)未被继承。
- 先在系统终端(非 VSCode 内置终端)执行
bun --version,确认安装成功;失败则重装:curl -fsSL https://bun.sh/install | bash - VSCode 必须从终端启动:
code .,而不是双击图标 —— 否则不继承 shell 环境变量 - Windows 用户若用 PowerShell,需临时允许脚本:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser - 不建议在
settings.json里硬写terminal.integrated.env.*补 PATH —— 容易漏路径、跨 Shell 失效;优先走code .启动
调试 JS/TS 文件时 launch.json 怎么配 bun
VSCode 默认的 Node.js 调试配置对 bun 无效,会卡在 “Waiting for debugger to attach”。必须用 pwa-node 类型,并显式指定 --inspect-brk。
-
type设为"pwa-node"(不是node) -
runtimeExecutable填"bun"(依赖 PATH,别写绝对路径) -
runtimeArgs包含--inspect-brk和入口文件,例如:["--inspect-brk", "index.ts"] -
console设为"integratedTerminal",避免调试器抢 stdin - 端口默认是 9229,不要改;如果冲突,可在
runtimeArgs加--inspect-brk=9230并同步改port字段
怎么让 VSCode 的测试侧边栏识别 bun test
VSCode 测试 UI 不原生支持 Bun,必须靠插件 + tasks.json 配合才能显示、运行、跳转测试用例。
- 装插件:
Bun Test Explorer(官方推荐,非微软第一方) - 项目根目录建
.vscode/tasks.json,label必须是"test",且group设为"test" -
command推荐写"npx bun test",比裸"bun test"更稳定(规避 PATH 问题) - 测试文件名必须符合 Bun 规范:
*.test.{js,ts}或*.spec.{js,ts},大小写敏感;utils_test.ts或Utils.test.ts都不会被发现 - 测试文件位置:放在
test/目录下,或与源码同级(如src/index.ts对应src/index.test.ts)
bun run --watch 和 VSCode 自动保存格式化冲突怎么解
两者同时监听同一文件,会导致 EMFILE: too many open files 或反复重启进程。
- 禁用自动格式化:
"editor.formatOnSave": false(写在工作区settings.json中) - 手动格式化用快捷键:
Shift+Alt+F(Windows/Linux)或Shift+Option+F(macOS) - 用
--watch-ignore排除干扰目录:bun run --watch --watch-ignore=node_modules --watch-ignore=dist index.ts - 别依赖 VSCode 的保存触发构建 ——
bun watch本身已足够快,无需叠加
PATH 加载和调试配置是最容易卡住的两个点,其他问题基本都由这两处衍生。一旦 bun --version 在 VSCode 终端能跑通,剩下就是照着 pwa-node 和 tasks.json 的字段填准,别抄错大小写和引号。











