入门
让我们使用内置的 Bun.serve
API 编写一个简单的 HTTP 服务器吧。首先,创建一个新目录。
$ mkdir quickstart
$ cd quickstart
运行 bun init
来创建一个新项目。这是一个交互式工具。在本教程中,只需按 enter
键接受每个默认设置即可。
$ bun init
bun init helps you get started with a minimal project and tries to
guess sensible defaults. Press ^C anytime to quit.
package name (quickstart):
entry point (index.ts):
Done! A package.json file was saved in the current directory.
+ index.ts
+ .gitignore
+ tsconfig.json (for editor auto-complete)
+ README.md
To get started, run:
bun run index.ts
由于我们的入口点是一个 *.ts
文件,Bun 会为您生成一个 tsconfig.json
配置文件。如果你使用的是纯 JavaScript,它会生成一个 jsconfig.json
配置文件。
运行文件
打开 index.ts
文件并粘贴下面的代码片段,这是一个用 Bun.serve
实现一个简单的 HTTP 服务器。
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Bun!");
},
});
console.log(`Listening on http://localhost:${server.port} ...`);
Seeing TypeScript errors on Bun
?
如果你使用的是 bun init
命令,Bun 会自动安装 Bun 的 TypeScript 声明,并为你配置 tsconfig.json
文件。如果你在现有项目中试用 Bun,可能会在 Bun
的 global 上看到类型错误提示。
要解决这个问题,请首先安装 @types/bun
作为开发依赖。
$ bun add -d @types/bun
然后在 tsconfig.json
中的添加 compilerOptions
配置项,内容如下:
{
"compilerOptions": {
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
}
}
在 shell 中运行上述文件。
$ bun index.ts
Listening on http://localhost:3000 ...
访问 http://localhost:3000 地址并测试服务器。你将看到一个简单的页面,上面写着 "Bun!"。
运行脚本
Bun 还可以执行 package.json
中的 "scripts"
配置项中的命令。添加以下脚本:
{
"name": "quickstart",
"module": "index.ts",
"type": "module",
+ "scripts": {
+ "start": "bun run index.ts"
+ },
"devDependencies": {
"@types/bun": "^1.0.0"
}
}
然后运行 bun run start
命令。
$ bun run start
$ bun run index.ts
Listening on http://localhost:3000 ...
⚡️ 性能 — bun run
大约比 npm run
快 28 倍(6ms 对比 170ms 的开销)。
安装软件包
让我们来安装一个软件包,让我们的服务器做一些更有趣的事。首先安装 figlet
软件包及其类型声明。Figlet 是一个将字符串转换为 ASCII 图像的工具。
$ bun add figlet
$ bun add -d @types/figlet # TypeScript users only
更新 index.ts
文件的内容,在 fetch
处理程序中使用 figlet
。
+ import figlet from "figlet";
const server = Bun.serve({
port: 3000,
fetch(req) {
+ const body = figlet.textSync("Bun!");
+ return new Response(body);
- return new Response("Bun!");
},
});
重新启动服务器并刷新页面。你会看到一个新的 ASCII 艺术画横幅。
____ _
| __ ) _ _ _ __ | |
| _ \| | | | '_ \| |
| |_) | |_| | | | |_|
|____/ \__,_|_| |_(_)