> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/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/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import my_toml from "./my_file" with { type: "toml" };
// 或使用动态导入
const { default: my_toml } = await import("./my_file", { with: { type: "toml" } });
```

## 内置加载器

### `js`

**JavaScript 加载器。** `.cjs` 和 `.mjs` 的默认值。

解析代码并应用一组默认转换，如死代码消除和 tree shaking。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={null}
import pkg from "./package.json";
pkg.name; // => "my-package"
```

打包期间，解析后的 JSON 会被内联到打包产物中作为 JavaScript 对象。

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

pkg.name;
```

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

<CodeGroup>
  ```json 输入 theme={null}
  {
    "name": "John Doe",
    "age": 35,
    "email": "johndoe@example.com"
  }
  ```

  ```js 输出 theme={null}
  export default {
    name: "John Doe",
    age: 35,
    email: "johndoe@example.com",
  };
  ```
</CodeGroup>

***

### `jsonc`

**带注释的 JSON 加载器。** `.jsonc` 的默认值。

JSONC（带注释的 JSON）文件可以直接导入。Bun 解析它们，剥离注释和尾随逗号。

```js theme={null}
import config from "./config.jsonc";
console.log(config);
```

打包期间，解析后的 JSONC 会被内联到打包产物中作为 JavaScript 对象，与 `json` 加载器相同。

```js theme={null}
var config = {
  option: "value",
};
```

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

***

### `toml`

**TOML 加载器。** `.toml` 的默认值。

TOML 文件可以直接导入。Bun 使用其原生 TOML 解析器解析它们。

```js theme={null}
import config from "./bunfig.toml";
config.logLevel; // => "debug"

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

打包期间，解析后的 TOML 会被内联到打包产物中作为 JavaScript 对象。

```js theme={null}
var config = {
  logLevel: "debug",
  // ... 其他字段
};
config.logLevel;
```

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

<CodeGroup>
  ```toml 输入 theme={null}
  name = "John Doe"
  age = 35
  email = "johndoe@example.com"
  ```

  ```js 输出 theme={null}
  export default {
    name: "John Doe",
    age: 35,
    email: "johndoe@example.com",
  };
  ```
</CodeGroup>

***

### `yaml`

**YAML 加载器。** `.yaml` 和 `.yml` 的默认值。

YAML 文件可以直接导入。Bun 使用其原生 YAML 解析器解析它们。

```js theme={null}
import config from "./config.yaml";
console.log(config);

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

打包期间，解析后的 YAML 会被内联到打包产物中作为 JavaScript 对象。

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

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

<CodeGroup>
  ```yaml 输入 theme={null}
  name: John Doe
  age: 35
  email: johndoe@example.com
  ```

  ```js 输出 theme={null}
  export default {
    name: "John Doe",
    age: 35,
    email: "johndoe@example.com",
  };
  ```
</CodeGroup>

***

### `text`

**文本加载器。** `.txt` 的默认值。

文本文件可以直接导入。文件被读取并作为字符串返回。

```js theme={null}
import contents from "./file.txt";
console.log(contents); // => "Hello, world!"

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

在构建中引用时，内容会被内联到打包产物中作为字符串。

```js theme={null}
var contents = `Hello, world!`;
console.log(contents);
```

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

<CodeGroup>
  ```txt 输入 theme={null}
  Hello, world!
  ```

  ```js 输出 theme={null}
  export default "Hello, world!";
  ```
</CodeGroup>

***

### `napi`

**原生插件加载器。** `.node` 的默认值。

在运行时中，原生插件可以直接导入。

```js theme={null}
import addon from "./addon.node";
console.log(addon);
```

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

***

### `sqlite`

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

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

```js theme={null}
import db from "./my.db" with { type: "sqlite" };
```

<Warning>当目标为 `bun` 时，`sqlite` 加载器才受支持。</Warning>

默认情况下，磁盘上的数据库文件不会被打包到最终输出中；它保持对打包产物的外部引用，因此你可以使用其他地方加载的数据库。

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

```js theme={null}
// 将数据库嵌入到打包产物中
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={null}
<!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>
```

Bun 输出一个新的 HTML 文件，其中包含打包后的资源：

```html title="dist/index.html" icon="file-code" theme={null}
<!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) 将 script 和 link 标签提取为入口点，将其他资源作为外部文件处理。

<Accordion title="支持的 HTML 选择器列表">
  支持的选择器有：

  * `audio[src]`
  * `img[src]`
  * `img[srcset]`
  * `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 文件可以直接导入。打包器解析并打包它们，处理 `@import` 语句和 `url()` 引用。

```js theme={null}
import "./styles.css";
```

打包期间，所有导入的 CSS 文件会被打包在一起，生成输出目录中的一个 `.css` 文件。

```css theme={null}
.my-class {
  background: url("./image.png");
}
```

***

### `sh`

**Bun Shell 加载器。** `.sh` 文件的默认值。

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

```bash theme={null}
bun run ./script.sh
```

***

### `file`

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

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

```js theme={null}
// logo.ts
import logo from "./logo.svg";
console.log(logo);
```

在运行时中，Bun 检查 `logo.svg` 是否存在，并将导入解析为其在磁盘上的绝对路径。

```bash theme={null}
bun run logo.ts
# 输出：/path/to/project/logo.svg
```

在打包器中，文件会被原样复制到 `outdir` 中，导入解析为指向复制文件的相对路径。

```js theme={null}
// 输出
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` 的值决定。</Note>
