You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让SvelteKit识别Bun变量?解决Bun API调用报错

解决SvelteKit无法识别Bun变量的问题

核心原因

SvelteKit默认未包含Bun的全局变量类型定义,导致TypeScript/ESLint报错;另外需注意Bun API仅能在服务器端环境执行,不能在客户端组件中调用。

具体解决步骤

1. 添加Bun类型定义

安装Bun的类型包,让TypeScript识别Bun全局变量:

bun add -D @types/bun

修改项目tsconfig.json,在types数组中加入bun:

{
  "compilerOptions": {
    // 保留原有配置
    "types": ["bun", "@sveltejs/kit"]
  }
}

2. 确保代码在服务器端执行

Bun的文件操作属于服务器端逻辑,必须放在以下位置:

  • 服务器路由文件(+server.ts/js)
  • 页面/布局的load函数(需添加export const ssr = true确保在服务器端运行)
  • 服务器端hooks文件(hooks.server.ts/js)

示例(服务器路由):

// src/routes/api/write-file/+server.js
export async function POST({ request }) {
  const { pathname, file } = await request.json();
  // 此处可安全调用Bun.write
  await Bun.write(pathname, new Uint8Array(await file.arrayBuffer()));
  return new Response(JSON.stringify({ success: true }), { status: 200 });
}

3. 消除ESLint报错(可选)

若ESLint仍提示Bun is not defined,在项目根目录的.eslintrc.cjs中声明全局变量:

module.exports = {
  // 保留原有配置
  globals: {
    Bun: 'readonly'
  }
};

验证

重启开发服务器(bun run dev),检查报错是否消失;同时测试文件写入功能,确保逻辑未在客户端触发。

内容的提问来源于stack exchange,提问作者angry kiwi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 19:58:10