Bun 将 TypeScript 视为一等公民。
注意 — 要为 Bun API(如 Bun
全局对象)添加类型声明,请按照 简介 > TypeScript 中的说明进行操作。本页面介绍 Bun 运行时如何运行 TypeScript 代码。
运行 .ts
文件
Bun 可以直接执行 .ts
和 .tsx
文件,就像原生 JavaScript 一样,无需任何额外配置。如果您导入一个 .ts
或 .tsx
文件(或导出这些文件的 npm
模块),Bun 会在内部将其转换为 JavaScript,然后执行该文件。
注意 — 与其他构建工具类似,Bun 不会进行类型检查。如果您想捕获静态类型错误,请使用 tsc
(官方 TypeScript CLI)。
是否仍需要转译? — 由于 Bun 可以直接执行 TypeScript,您可能无需在生产环境中转译 TypeScript。Bun 在内部转译它执行的每个文件(包括 .js
和 .ts
),因此直接执行 .ts/.tsx
源文件的额外开销可以忽略不计。
但是,如果您将 Bun 用作开发工具,但在生产环境中仍以 Node.js 或浏览器为目标,则仍需要转译。
路径映射
在解析模块时,Bun 的运行时会遵循 tsconfig.json
中定义的 compilerOptions.paths
中的路径映射。没有其他运行时会这样做。
考虑以下 tsconfig.json
。
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"data": ["./data.ts"]
}
}
}
Bun 将使用 baseUrl
来解析模块路径。
// resolves to ./src/components/Button.tsx
import { Button } from "components/Button.tsx";
Bun 还会正确解析来自 "data"
的导入。
import { foo } from "data";
console.log(foo); // => "Hello world!"
export const foo = "Hello world!"
实验性装饰器
Bun 支持 TypeScript 5.0 之前的实验性装饰器语法。
// Simple logging decorator
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with:`, args);
return originalMethod.apply(this, args);
};
}
class Example {
@log
greet(name: string) {
return `Hello ${name}!`;
}
}
// Usage
const example = new Example();
example.greet("world"); // Logs: "Calling greet with: ['world']"
要启用它,请在 tsconfig.json
中添加 "experimentalDecorators": true
。
{
"compilerOptions": {
// ... rest of your config
"experimentalDecorators": true,
},
}
我们通常不建议在新代码库中使用此功能,但许多现有代码库已经依赖它。
emitDecoratorMetadata
Bun 支持 tsconfig.json
中的 emitDecoratorMetadata
。这可以在源文件中为被装饰的声明发出设计时类型元数据。
import "reflect-metadata";
class User {
id: number;
name: string;
}
function Injectable(target: Function) {
// Get metadata about constructor parameters
const params = Reflect.getMetadata("design:paramtypes", target);
console.log("Dependencies:", params); // [User]
}
@Injectable
class UserService {
constructor(private user: User) {}
}
// Creates new UserService instance with dependencies
const container = new UserService(new User());
要启用它,请在 tsconfig.json
中添加 "emitDecoratorMetadata": true
。
{
"compilerOptions": {
// ... rest of your config
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
},
}