> ## 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` `.json5` `.toml` `.yaml` `.yml` `.txt` `.wasm` `.node` `.html` `.sh`

Bun 使用文件扩展名来选择解析文件的内置\_加载器\_。每个加载器都有一个名称，如 `js`、`tsx` 或 `json`。这些名称在构建[插件](/bundler/plugins)时使用，以扩展 Bun 的自定义加载器。

要显式指定加载器，请使用 `type` 导入属性。

```ts 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` 的默认加载器。

解析代码并应用一组默认转换，如死代码消除和摇树优化。Bun 不会降级语法。

### `jsx`

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

与 `js` 加载器相同，但支持 JSX 语法。默认情况下，JSX 被降级为纯 JavaScript；具体细节取决于 `tsconfig.json` 中的 `jsx*` 编译器选项。请参阅 TypeScript 文档[关于 JSX](https://www.typescriptlang.org/docs/handbook/jsx.html)。

### `ts`

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

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

### `tsx`

**TypeScript + JSX 加载器**。`.tsx` 的默认加载器。将 TypeScript 和 JSX 都转译为普通 JavaScript。

### `json`

**JSON 加载器**。`.json` 的默认加载器。

JSON 文件可以直接导入。

```ts theme={null}
import pkg from "./package.json";
pkg.name; // => "my-package"
```

在打包期间，解析后的 JSON 会作为 JavaScript 对象内联到打包结果中。

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

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

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

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

### `jsonc`

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

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

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

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

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

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

### `toml`

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

TOML 文件可以直接导入。Bun 使用其快速的原生 TOML 解析器进行解析。

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

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

在打包期间，解析后的 TOML 会作为 JavaScript 对象内联到打包结果中。

```ts 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"
  ```

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

### `yaml`

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

YAML 文件可以直接导入。Bun 使用其快速的原生 YAML 解析器进行解析。

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

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

在打包期间，解析后的 YAML 会作为 JavaScript 对象内联到打包结果中。

```ts 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
  ```

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

### `json5`

**JSON5 加载器**。`.json5` 的默认加载器。

JSON5 文件可以直接导入。Bun 使用其快速的原生 JSON5 解析器进行解析。JSON5 是 JSON 的超集，增加了注释、尾随逗号、未加引号的键、单引号字符串等。

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

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

在打包期间，解析后的 JSON5 会作为 JavaScript 对象内联到打包结果中。

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

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

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

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

### `text`

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

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

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

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

在构建过程中引用时，内容会作为字符串内联到打包结果中。

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

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

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

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

### `napi`

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

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

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

在打包器中，`.node` 文件使用 [`file`](#file) 加载器处理。

### `sqlite`

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

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

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

这仅在 `target` 为 `bun` 时支持。

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

你可以通过 `"embed"` 属性更改此行为：

```ts theme={null}
// 将数据库嵌入到打包结果中
import db from "./my.db" with { type: "sqlite", embed: "true" };
```

使用[独立可执行文件](/bundler/executables)时，数据库会被嵌入到单文件可执行文件中。

否则，要嵌入的数据库会被复制到 `outdir` 并使用哈希文件名。

### `html`

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

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

例如，给定这个 HTML 文件：

<CodeGroup>
  ```html src/index.html 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>
  ```
</CodeGroup>

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

<CodeGroup>
  ```html dist/output.html 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>
  ```
</CodeGroup>

该加载器使用 [`lol-html`](https://github.com/cloudflare/lol-html) 将 script 和 link 标签提取为入口点，将其他资源提取为外部资源。

选择器列表如下：

* `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]`

<Note>
  **HTML 加载器在不同上下文中的行为**

  `html` 加载器根据使用方式不同而有不同行为：

  1. **静态构建：** 运行 `bun build ./index.html` 时，Bun 生成一个所有资源都经过打包和哈希的静态站点。

  2. **运行时：** 运行 `bun run server.ts`（其中 `server.ts` 导入了 HTML 文件）时，Bun 在开发过程中动态打包资源，启用热模块替换等功能。

  3. **全栈构建：** 运行 `bun build --target=bun server.ts`（其中 `server.ts` 导入了 HTML 文件）时，导入会解析为一个清单对象，`Bun.serve` 在生产环境中使用该对象高效地提供预打包资源。
</Note>

### `css`

**CSS 加载器**。`.css` 的默认加载器。

CSS 文件可以直接导入。这主要用于[全栈应用](/bundler/html-static)，其中 CSS 与 HTML 一起打包。

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

导入不会返回任何值；它仅用于其副作用。

### `sh` 加载器

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

此加载器解析 [Bun Shell](/runtime/shell) 脚本。仅支持在启动 Bun 本身时使用，因此在打包器或运行时中不可用。

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

### `file`

**文件加载器**。所有无法识别的文件类型的默认加载器。

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

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

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

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

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

```ts 输出 theme={null}
var logo = "./logo.svg";
console.log(logo);
```

如果设置了 `publicPath`，导入会使用其值作为前缀来构建绝对路径/URL。

| Public path                  | 解析后的导入                             |
| ---------------------------- | ---------------------------------- |
| `""` (默认)                    | `./logo.svg`                       |
| `"/assets/"`                 | `/assets/logo.svg`                 |
| `"https://cdn.example.com/"` | `https://cdn.example.com/logo.svg` |

<Note>
  复制文件的位置和文件名由 [`naming.asset`](/bundler#naming) 的值决定。
</Note>

<Accordion title="修复 TypeScript 导入错误">
  如果你使用 TypeScript，可能会遇到如下错误：

  ```ts theme={null}
  // TypeScript 错误
  // Cannot find module './logo.svg' or its corresponding type declarations.
  ```

  要修复此问题，在项目中的任意位置创建一个 `*.d.ts` 文件（文件名任意），内容如下：

  ```ts theme={null}
  declare module "*.svg" {
    const content: string;
    export default content;
  }
  ```

  这告诉 TypeScript，来自 `.svg` 的任何默认导入都应被视为字符串。
</Accordion>
