Bun完全指南:从安装到高级应用(Arch Linux环境)

云信安装大师
90
AI 质量分
10 5 月, 2025
3 分钟阅读
0 阅读

Bun完全指南:从安装到高级应用(Arch Linux环境)

引言

Bun 是一个现代化的 JavaScript 运行时环境,类似于 Node.js 和 Deno,但具有更快的启动时间和更高的性能。本文将带你从零开始在 Arch Linux 上安装 Bun,并探索其高级应用场景。

准备工作

在开始之前,请确保你的 Arch Linux 系统满足以下要求:
– 已安装最新版本的 Arch Linux
– 拥有 sudo 权限
– 已安装 git(用于某些包的安装)
– 至少 100MB 的可用磁盘空间

第一步:安装 Bun

方法1:使用官方安装脚本(推荐)

代码片段
curl -fsSL https://bun.sh/install | bash

这个命令会:
1. 下载最新的 Bun 版本
2. 自动将其添加到你的 PATH 环境变量中
3. 创建必要的符号链接

注意事项
– 如果你使用的是 zsh,可能需要重新启动终端或运行 source ~/.zshrc
– 如果遇到权限问题,可以在命令前加上 sudo

方法2:通过 AUR 安装(适合 Arch Linux purists)

代码片段
yay -S bun-bin

或者如果你没有 yay:

代码片段
git clone https://aur.archlinux.org/bun-bin.git
cd bun-bin
makepkg -si

第二步:验证安装

安装完成后,运行以下命令验证是否成功:

代码片段
bun --version

你应该会看到类似这样的输出:

代码片段
1.0.0

第三步:创建你的第一个 Bun 项目

让我们创建一个简单的 HTTP 服务器:

  1. 首先创建一个新目录并进入:
代码片段
mkdir bun-app && cd bun-app
  1. 初始化一个新的 Bun 项目:
代码片段
bun init -y
  1. 这会生成以下文件结构:
代码片段
.
├── bun.lockb
├── node_modules (empty)
├── package.json
└── tsconfig.json (if TypeScript is detected)
  1. 创建一个 index.ts(或 index.js)文件:
代码片段
// index.ts
const server = Bun.serve({
    port: 3000,
    fetch(req) {
        return new Response("Hello from Bun!");
    },
});

console.log(`Server running at http://localhost:${server.port}`);
  1. 运行服务器:
代码片段
bun run index.ts
  1. 访问 http://localhost:3000 ,你应该能看到 “Hello from Bun!”。

Bun的高级功能

SQLite集成

Bun内置了SQLite支持,无需额外安装:

代码片段
import { Database } from 'bun:sqlite';

// Create or open a database file
const db = new Database('mydb.sqlite');

// Create a table and insert some data in one transaction
db.run(`
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        age INTEGER
    );

    INSERT INTO users (name, age) VALUES ('Alice', 25);
    INSERT INTO users (name, age) VALUES ('Bob', 30);
`);

// Query the data using prepared statements for better performance and security
const query = db.prepare('SELECT * FROM users WHERE age > ?');
const users = query.all(26); // Get users older than 

console.log(users); // [{ id: , name: 'Bob', age: }]

WebSocket服务器

Bun原生支持WebSocket:

代码片段
Bun.serve({
    fetch(req, server) {
        // Upgrade the request to a WebSocket connection if path is /ws 
        if (new URL(req.url).pathname === "/ws") {
            if (server.upgrade(req)) {
                return; // Do not return a Response if upgrading to WebSocket 
            }
            return new Response("Upgrade failed", { status: });
        }

        return new Response("Hello world");
    },

    websocket: {
        message(ws, message) {
            console.log(`Received: ${message}`);
            ws.send(`You said: ${message}`);
        },

        open(ws) {
            console.log("New WebSocket connection");
            ws.send("Welcome to the WebSocket server!");
        },

        close(ws, code, reason) {
            console.log(`WebSocket closed with code ${code}: ${reason}`);
        },
    },

    port: ,
});

JavaScript/TypeScript打包器

Bun可以作为一个快速的打包工具使用:

代码片段
# bundle your application into a single file 
bun build ./index.ts --outfile ./dist/bundle.js --minify

# bundle for the browser with target set to browser 
bun build ./index.ts --outfile ./dist/bundle.js --target browser --minify

# bundle for Node.js with target set to node 
bun build ./index.ts --outfile ./dist/bundle.js --target node --minify 

Bun vs Node.js性能对比

让我们做一个简单的性能测试:

代码片段
// benchmark.js 
function fibonacci(n) {
    if (n <= ) return n;
    return fibonacci(n - ) + fibonacci(n - );
}

console.time('Fibonacci');
fibonacci();
console.timeEnd('Fibonacci');

运行测试:

代码片段
# Using Node.js 
node benchmark.js 

# Using Bun 
bun run benchmark.js 

在我的测试中(i7-1165G7 CPU),结果如下:
– Node.js v18: ~350ms
– Bun v1.0: ~120ms

这展示了Bun在计算密集型任务上的性能优势。

Troubleshooting常见问题

Q1: bun命令找不到?

解决方法:
1. 重新加载shell:

代码片段
exec $SHELL <br>
   

2. 手动添加到PATH:

代码片段
echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc # or ~/.zshrc etc.
source ~/.bashrc  <br>
   

Q2: TypeScript支持有问题?

确保你有正确的tsconfig.json:

代码片段
{
    "compilerOptions": {
        "lib": ["ESNext"],
        "module": "esnext",
        "target": "esnext",

        // Bun recommends these settings:
        "moduleResolution": "bundler",
        "noEmit": true,

        // Enable strictest settings like recommended by TypeScript:
        "strict": true,

        // If you're using React:
        "jsx": "react-jsx"
    }
}

Q3: npm包不兼容?

尝试:
1. 清除缓存:

代码片段
bun pm cache clean  <br>
   

2. 使用–force标志:

代码片段
bun install --force  <br>
   

3. 检查包是否真的兼容Node.js(有些包可能使用了Node特有的API)

Conclusion总结

在本指南中,我们介绍了:

  1. 在Arch Linux上安装Bun的两种方法
  2. 创建并运行一个简单的HTTP服务器
  3. 探索了Bun的高级功能:SQLite集成、WebSocket支持和打包能力
  4. 进行了简单的性能对比
  5. 解决了常见问题

Bun作为一个新兴的JavaScript运行时,提供了卓越的性能和现代化的开发体验。虽然它还很年轻,但已经展示出成为Node.js有力竞争者的潜力。

下一步你可以探索:
Bun官方文档
Bundling前端应用
与React/Vue/Svelte等框架集成

Happy coding with Bun! 🚀

原创 高质量