> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 加载器

> Bun 打包器和运行时内置加载器

Bun 打包器开箱即用实现了一组默认加载器。

> 通常规则是：**打包器和运行时都支持相同的一组文件类型。**

`.js` `.cjs` `.mjs` `.mts` `.cts` `.ts` `.tsx` `.jsx` `.css` `.json` `.jsonc` `.toml` `.yaml` `.yml` `.txt` `.wasm` `.node` `.html` `.sh`

Bun 使用文件扩展名来确定应该使用哪个内置加载器解析文件。每个加载器都有一个名称，比如 `js`、`tsx` 或 `json`。这些名称用于构建扩展 Bun 的自定义加载器插件时。

你可以使用 `'type'` 导入属性显式指定使用哪个加载器。

```ts title="index.ts" icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import my_toml from "./my_file" with { type: "toml" };
// 或使用动态导入
const { default: my_toml } = await import("./my_file", { with: { type: "toml" } });
```

## 内置加载器

### `js`

**JavaScript 加载器。** 默认用于 `.cjs` 和 `.mjs`。

解析代码并应用一组默认转换，如死代码消除和摇树优化。注意目前 Bun 不尝试对语法进行向下转换。

***

### `jsx`

**JavaScript + JSX 加载器。** 默认用于 `.js` 和 `.jsx`。

与 `js` 加载器相同，但支持 JSX 语法。默认情况下，JSX 会被向下转换成普通 JavaScript；转换的具体方式依赖于你 `tsconfig.json` 中的 `jsx*` 编译选项。详情请参考 [TypeScript 关于 JSX 的文档](https://www.typescriptlang.org/tsconfig#jsx)。

***

### `ts`

**TypeScript 加载器。** 默认用于 `.ts`、`.mts` 和 `.cts`。

剥离所有 TypeScript 语法，然后行为与 `js` 加载器完全相同。Bun 不执行类型检查。

***

### `tsx`

**TypeScript + JSX 加载器。** 默认用于 `.tsx`。

将 TypeScript 和 JSX 转译成普通 JavaScript。

***

### `json`

**JSON 加载器。** 默认用于 `.json`。

可以直接导入 JSON 文件。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
import pkg from "./package.json";
pkg.name; // => "my-package"
```

在打包时，解析后的 JSON 会以内联的 JavaScript 对象形式插入到包内。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
const pkg = {
  name: "my-package",
  // ... 其他字段
};

pkg.name;
```

如果 `.json` 文件作为打包入口传入，它会被转换成一个 `.js` 模块，`export default` 导出解析后的对象。

<CodeGroup>
  ```json Input theme={"theme":{"light":"github-light","dark":"dracula"}}
  {
    "name": "John Doe",
    "age": 35,
    "email": "johndoe@example.com"
  }
  ```

  ```js Output theme={"theme":{"light":"github-light","dark":"dracula"}}
  export default {
    name: "John Doe",
    age: 35,
    email: "johndoe@example.com",
  };
  ```
</CodeGroup>

***

### `jsonc`

**含注释的 JSON（JSONC）加载器。** 默认用于 `.jsonc`。

可以直接导入 JSONC（带注释的 JSON）文件。Bun 会解析并去除注释和尾随逗号。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
import config from "./config.jsonc";
console.log(config);
```

打包时，解析后的 JSONC 会以内联的 JavaScript 对象形式插入包内，与 `json` 加载器相同。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
var config = {
  option: "value",
};
```

<Note>
  Bun 会自动针对 `tsconfig.json`、`jsconfig.json`、`package.json` 和 `bun.lock` 文件使用 `jsonc` 加载器。
</Note>

***

### `toml`

**TOML 加载器。** 默认用于 `.toml`。

可以直接导入 TOML 文件。Bun 使用其快速的本地 TOML 解析器解析。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
import config from "./bunfig.toml";
config.logLevel; // => "debug"

// 通过导入属性：
// import myCustomTOML from './my.config' with {type: "toml"};
```

打包时，解析后的 TOML 会以内联的 JavaScript 对象形式插入包内。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
var config = {
  logLevel: "debug",
  // ...其他字段
};
config.logLevel;
```

如果 `.toml` 文件作为打包入口传入，它会被转换成一个 `.js` 模块，`export default` 导出解析后的对象。

<CodeGroup>
  ```toml Input theme={"theme":{"light":"github-light","dark":"dracula"}}
  name = "John Doe"
  age = 35
  email = "johndoe@example.com"
  ```

  ```js Output theme={"theme":{"light":"github-light","dark":"dracula"}}
  export default {
    name: "John Doe",
    age: 35,
    email: "johndoe@example.com",
  };
  ```
</CodeGroup>

***

### `yaml`

**YAML 加载器。** 默认用于 `.yaml` 和 `.yml`。

可以直接导入 YAML 文件。Bun 使用它快速的本地 YAML 解析器解析。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
import config from "./config.yaml";
console.log(config);

// 通过导入属性：
import data from "./data.txt" with { type: "yaml" };
```

打包时，解析后的 YAML 会以内联的 JavaScript 对象形式插入包内。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
var config = {
  name: "my-app",
  version: "1.0.0",
  // ...其他字段
};
```

如果 `.yaml` 或 `.yml` 文件作为打包入口传入，它会被转换成一个 `.js` 模块，`export default` 导出解析后的对象。

<CodeGroup>
  ```yaml Input theme={"theme":{"light":"github-light","dark":"dracula"}}
  name: John Doe
  age: 35
  email: johndoe@example.com
  ```

  ```js Output theme={"theme":{"light":"github-light","dark":"dracula"}}
  export default {
    name: "John Doe",
    age: 35,
    email: "johndoe@example.com",
  };
  ```
</CodeGroup>

***

### `text`

**文本加载器。** 默认用于 `.txt`。

将文本文件内容读取并以内联字符串的形式插入包内。可以直接导入文本文件。文件内容会被读取并作为字符串返回。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
import contents from "./file.txt";
console.log(contents); // => "Hello, world!"

// 导入 html 文件作为文本
// 可以使用 "type" 属性覆盖默认加载器。
import html from "./index.html" with { type: "text" };
```

构建时，文件内容以内联字符串形式插入包内。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
var contents = `Hello, world!`;
console.log(contents);
```

如果 `.txt` 文件作为入口传入，会被转换成一个 `.js` 模块，`export default` 导出文件内容。

<CodeGroup>
  ```txt Input theme={"theme":{"light":"github-light","dark":"dracula"}}
  Hello, world!
  ```

  ```js Output theme={"theme":{"light":"github-light","dark":"dracula"}}
  export default "Hello, world!";
  ```
</CodeGroup>

***

### `napi`

**本地扩展加载器。** 默认用于 `.node`。

在运行时，可以直接导入本地扩展。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
import addon from "./addon.node";
console.log(addon);
```

<Note>在打包器中，`.node` 文件使用文件加载器处理。</Note>

***

### `sqlite`

**SQLite 加载器。** 需要使用 `with { "type": "sqlite" }` 导入属性。

运行时和打包器中可以直接导入 SQLite 数据库文件。将使用 `bun:sqlite` 加载数据库。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
import db from "./my.db" with { type: "sqlite" };
```

<Warning>此功能仅在目标是 `bun` 时支持。</Warning>

默认情况下，数据库文件是包外部的（这样你可以在别处加载数据库），因此磁盘上的数据库文件不会打包进最终产物。

你可以使用 `"embed"` 属性改变此行为：

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
// 将数据库嵌入包内
import db from "./my.db" with { type: "sqlite", embed: "true" };
```

<Info>
  使用独立可执行文件时，数据库会嵌入独立可执行文件内。

  否则，嵌入的数据库会被复制到输出目录 `outdir`，并带有哈希文件名。
</Info>

***

### `html`

**HTML 加载器。** 默认用于 `.html`。

`html` 加载器处理 HTML 文件，并打包所有引用的资源。它会：

* 打包并哈希引用的 JavaScript 文件（`<script src="...">`）
* 打包并哈希引用的 CSS 文件（`<link rel="stylesheet" href="...">`）
* 哈希引用的图片（`<img src="...">`）
* 保留外部 URL（默认以 `http://` 或 `https://` 开头的）

例如，给定如下 HTML 文件：

```html title="src/index.html" icon="file-code" theme={"theme":{"light":"github-light","dark":"dracula"}}
<!DOCTYPE html>
<html>
  <body>
    <img src="./image.jpg" alt="本地图片" />
    <img src="https://example.com/image.jpg" alt="外部图片" />
    <script type="module" src="./script.js"></script>
  </body>
</html>
```

它将输出新的 HTML 文件，引用打包后的资源：

```html title="dist/index.html" icon="file-code" theme={"theme":{"light":"github-light","dark":"dracula"}}
<!DOCTYPE html>
<html>
  <body>
    <img src="./image-HASHED.jpg" alt="本地图片" />
    <img src="https://example.com/image.jpg" alt="外部图片" />
    <script type="module" src="./output-ALSO-HASHED.js"></script>
  </body>
</html>
```

其底层使用了 [`lol-html`](https://github.com/cloudflare/lol-html) 来提取脚本和链接标签作为入口点，其他资源视为外部资源。

<Accordion title="支持的 HTML 选择器列表">
  当前支持的选择器包括：

  * `audio[src]`
  * `iframe[src]`
  * `img[src]`
  * `img[srcset]`
  * `link:not([rel~='stylesheet']):not([rel~='modulepreload']):not([rel~='manifest']):not([rel~='icon']):not([rel~='apple-touch-icon'])[href]`
  * `link[as='font'][href], link[type^='font/'][href]`
  * `link[as='image'][href]`
  * `link[as='style'][href]`
  * `link[as='video'][href], link[as='audio'][href]`
  * `link[as='worker'][href]`
  * `link[rel='icon'][href], link[rel='apple-touch-icon'][href]`
  * `link[rel='manifest'][href]`
  * `link[rel='stylesheet'][href]`
  * `script[src]`
  * `source[src]`
  * `source[srcset]`
  * `video[poster]`
  * `video[src]`
</Accordion>

<Note>
  **HTML 加载器在不同场景下的行为**

  `html` 加载器的行为取决于它的使用方式：

  * 静态构建：运行 `bun build ./index.html` 时，Bun 生成包含所有资源的静态站点，且资源已打包并哈希。
  * 运行时：运行 `bun run server.ts`（其中 `server.ts` 导入 HTML 文件）时，Bun 开发期间动态打包资源，支持热模块替换等功能。
  * 全栈构建：运行 `bun build --target=bun server.ts`（其中 `server.ts` 导入 HTML 文件）时，导入解析为清单对象，供 `Bun.serve` 高效地在生产环境提供预打包资源。
</Note>

***

### `css`

**CSS 加载器。** 默认用于 `.css`。

可以直接导入 CSS 文件。打包器会解析并打包 CSS 文件，支持 `@import` 语句和 `url()` 引用。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
import "./styles.css";
```

打包时，所有导入的 CSS 文件会合并成一个单独的 `.css` 文件输出到目标目录。

```css theme={"theme":{"light":"github-light","dark":"dracula"}}
.my-class {
  background: url("./image.png");
}
```

***

### `sh`

**Bun Shell 加载器。** 默认用于 `.sh` 文件。

此加载器用于解析 Bun Shell 脚本。仅在启动 Bun 本身时支持，因此在打包器或运行时不可用。

```bash theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run ./script.sh
```

***

### `file`

**文件加载器。** 默认用于所有未识别的文件类型。

该加载器将导入解析为导入文件的路径或 URL，通常用于引用媒体或字体资源。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
// logo.ts
import logo from "./logo.svg";
console.log(logo);
```

在运行时，Bun 会检查 `logo.svg` 文件是否存在，并将其转换为该文件在磁盘上的绝对路径。

```bash theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run logo.ts
# 输出: /path/to/project/logo.svg
```

在打包器中，情况略有不同。文件会原样复制到输出目录 `outdir`，导入解析为指向复制文件的相对路径。

```js theme={"theme":{"light":"github-light","dark":"dracula"}}
// 输出
var logo = "./logo.svg";
console.log(logo);
```

如果为 `publicPath` 指定了值，导入会使用该值作为前缀，构造绝对路径或 URL。

| 公共路径                         | 解析导入                               |
| ---------------------------- | ---------------------------------- |
| `""`（默认）                     | `/logo.svg`                        |
| `"/assets"`                  | `/assets/logo.svg`                 |
| `"https://cdn.example.com/"` | `https://cdn.example.com/logo.svg` |

<Note>
  复制的文件位置和文件名由 `naming.asset` 的值决定。

  此加载器将文件原样复制到 `outdir`，复制文件名根据 `naming.asset` 决定。
</Note>
