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

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

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

```ts 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/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={"theme":{"light":"github-light","dark":"dracula"}}
import pkg from "./package.json";
pkg.name; // => "my-package"
```

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

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
var 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"
  }
  ```

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

### `jsonc`

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

支持带注释的 JSONC 文件直接导入。Bun 解析时会移除注释和尾随逗号。

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

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

```ts 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 解析器进行解析。

```ts 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 对象形式嵌入包中。

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

  ```ts 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 解析器进行解析。

```ts 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 对象形式嵌入包中。

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

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

### `json5`

**JSON5 loader**. Default for `.json5`.

JSON5 files can be directly imported. Bun will parse them with its fast native JSON5 parser. JSON5 is a superset of JSON that supports comments, trailing commas, unquoted keys, single-quoted strings, and more.

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

// via import attribute:
import data from "./data.txt" with { type: "json5" };
```

During bundling, the parsed JSON5 is inlined into the bundle as a JavaScript object.

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
var config = {
  name: "my-app",
  version: "1.0.0",
  // ...other fields
};
```

If a `.json5` file is passed as an entrypoint, it will be converted to a `.js` module that `export default`s the parsed object.

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

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

### `text`

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

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

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

构建时，内容会以内联的字符串形式嵌入包中。

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

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

### `napi`

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

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

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

打包时，`.node` 文件由 [`file`](#file) 加载器处理。

### `sqlite`

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

运行时和打包时都支持直接导入 SQLite 数据库文件，内部通过 [`bun:sqlite`](/runtime/sqlite) 加载。

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

仅当 `target` 为 `bun` 时支持。

默认情况下，数据库文件不会被打包进最终文件（保持外部），方便你在其他地方加载数据库。

你可以通过 `"embed"` 属性改变这个行为：

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
// 将数据库嵌入包中
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://` 开头的链接）

示例，假设有如下 HTML 文件：

<CodeGroup>
  ```html src/index.html theme={"theme":{"light":"github-light","dark":"dracula"}}
  <!DOCTYPE html>
  <html>
    <body>
      <img src="./image.jpg" alt="Local image" />
      <img src="https://example.com/image.jpg" alt="External image" />
      <script type="module" src="./script.js"></script>
    </body>
  </html>
  ```
</CodeGroup>

输出将是一个新的 HTML 文件，包含打包好的资源：

<CodeGroup>
  ```html dist/output.html theme={"theme":{"light":"github-light","dark":"dracula"}}
  <!DOCTYPE html>
  <html>
    <body>
      <img src="./image-HASHED.jpg" alt="Local image" />
      <img src="https://example.com/image.jpg" alt="External image" />
      <script type="module" src="./output-ALSO-HASHED.js"></script>
    </body>
  </html>
  ```
</CodeGroup>

内部使用 [`lol-html`](https://github.com/cloudflare/lol-html) 来提取 script 和 link 标签作为入口，其他资源作为外部资源。

当前支持的选择器列表：

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

<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={"theme":{"light":"github-light","dark":"dracula"}}
import "./styles.css";
```

导入不会返回任何值，只产生副作用。

### `sh` 加载器

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

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

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

### `file`

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

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

```ts logo.ts theme={"theme":{"light":"github-light","dark":"dracula"}}
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`，导入解析为指向复制文件的相对路径。

```ts Output 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`](/bundler#naming) 的值决定。
</Note>

此加载器复制文件到 `outdir`，复制文件名由
`naming.asset` 的值确定。

<Accordion title="解决 TypeScript 导入错误">
  如果你使用 TypeScript，可能会遇到类似错误：

  ```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
  // TypeScript 错误
  // 无法找到模块 './logo.svg' 或其对应的类型声明。
  ```

  可在项目中任意位置创建一个 `*.d.ts` 文件（名字随意），内容如下：

  ```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
  declare module "*.svg" {
    const content: string;
    export default content;
  }
  ```

  这告诉 TypeScript，所有默认导入 `.svg` 文件都应被视为字符串。
</Accordion>
