Skip to content
Closed
8 changes: 7 additions & 1 deletion docs/bundler/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,10 @@ Like the Bun runtime, the bundler supports a range of file types by default. The
| `.jsonc` | JSON with comments. Files are parsed and inlined into the bundle as a JavaScript object.<br/><br/>`js<br/>import config from "./config.jsonc";<br/>config.name; // => "my-config"<br/>` |
| `.toml` | TOML files are parsed and inlined into the bundle as a JavaScript object.<br/><br/>`js<br/>import config from "./bunfig.toml";<br/>config.logLevel; // => "debug"<br/>` |
| `.yaml` `.yml` | YAML files are parsed and inlined into the bundle as a JavaScript object.<br/><br/>`js<br/>import config from "./config.yaml";<br/>config.name; // => "my-app"<br/>` |
| `.txt` | The contents of the text file are read and inlined into the bundle as a string.<br/><br/>`js<br/>import contents from "./file.txt";<br/>console.log(contents); // => "Hello, world!"<br/>` |
| `.json5` | JSON5 files are parsed and inlined into the bundle as a JavaScript object.<br/><br/>`js<br/>import config from "./config.json5";<br/>config.name; // => "my-app"<br/>` |
| `.xml` | XML files are parsed into the compact object shape of [`Bun.XML.parse`](/runtime/xml) and inlined into the bundle.<br/><br/>`js<br/>import doc from "./config.xml";<br/>doc.config["@version"]; // => "2"<br/>` |
| `.txt` `.text` | The contents of the text file are read and inlined into the bundle as a string.<br/><br/>`js<br/>import contents from "./file.txt";<br/>console.log(contents); // => "Hello, world!"<br/>` |
| `.md` `.markdown` | Markdown files are rendered to HTML and inlined into the bundle as a string.<br/><br/>`js<br/>import html from "./README.md";<br/>console.log(html); // => "<h1>My project</h1>\n"<br/>` |
| `.html` | HTML files are processed and any referenced assets (scripts, stylesheets, images) are bundled. |
| `.css` | CSS files are bundled together into a single `.css` file in the output directory. |
| `.node` `.wasm` | These files are supported by the Bun runtime, but during bundling they are treated as assets. |
Expand Down Expand Up @@ -1792,8 +1795,11 @@ type Loader =
| "css"
| "json"
| "jsonc"
| "json5"
| "toml"
| "yaml"
| "xml"
| "md"
| "text"
| "file"
| "napi"
Expand Down
108 changes: 106 additions & 2 deletions docs/bundler/loaders.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ The Bun bundler has a set of built-in loaders.

> As a rule of thumb: **the bundler and the runtime both support the same set of file types by default.**

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

Bun uses the file extension to choose which built-in loader parses the file. Every loader has a name, such as `js`, `tsx`, or `json`. Plugins that extend Bun with custom loaders refer to these names.

Expand Down Expand Up @@ -216,6 +216,55 @@ export default {

---

### `json5`

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

JSON5 files can be directly imported. Bun parses them with its native [JSON5 parser](/runtime/json5). JSON5 is a superset of JSON that adds comments, trailing commas, unquoted keys, and single-quoted strings.

```js
import config from "./config.json5";
console.log(config);

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

During bundling, the parsed JSON5 is inlined into the bundle as a JavaScript object, identical to the `json` loader.

```js
var config = {
name: "my-app",
version: "1.0.0",
// ...other fields
};
```

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

<CodeGroup>

```json5 Input
{
// Configuration
name: "John Doe",
age: 35,
email: "johndoe@example.com",
}
```

```js Output
export default {
name: "John Doe",
age: 35,
email: "johndoe@example.com",
};
```

</CodeGroup>

---

### `xml`

**XML loader.** Default for `.xml`.
Expand Down Expand Up @@ -271,7 +320,7 @@ export default {

### `text`

**Text loader.** Default for `.txt`.
**Text loader.** Default for `.txt` and `.text`.

Text files can be directly imported. The file is read and returned as a string.

Expand Down Expand Up @@ -307,6 +356,61 @@ export default "Hello, world!";

---

### `md`

**Markdown loader.** Default for `.md` and `.markdown`.

Markdown files can be directly imported. Bun renders them to HTML with [`Bun.markdown`](/runtime/markdown), and the import resolves to the rendered HTML as a string.

```js
import html from "./README.md";
console.log(html); // => "<h1>My project</h1>\n..."

// with an import attribute:
import notes from "./notes.txt" with { type: "md" };
```

<Note>

`bun-types` does not declare a `*.md` module, because frameworks such as Astro declare their own `*.md` module and a second declaration would override their default export. To type the import in a plain Bun project, add a `.d.ts` file with the following, plus the same block for `"*.markdown"` if you use that extension:

```ts
declare module "*.md" {
const html: string;
export default html;
}
```

</Note>

During bundling, the rendered HTML is inlined into the bundle as a string.

```js
var README_default = `<h1>My project</h1>
<p>Some <strong>bold</strong> text.</p>
`;
```

If a `.md` file is passed as an entrypoint, it is converted to a `.js` module that `export default`s the rendered HTML.

<CodeGroup>

```md Input
# Hello

Some **bold** text.
```

```js Output
export default `<h1>Hello</h1>
<p>Some <strong>bold</strong> text.</p>
`;
```

</CodeGroup>

---

### `napi`

**Native addon loader.** Default for `.node`.
Expand Down
3 changes: 3 additions & 0 deletions docs/bundler/plugins.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,11 @@ type Loader =
| "tsx"
| "json"
| "jsonc"
| "json5"
| "toml"
| "yaml"
| "xml"
| "md"
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
| "file"
| "napi"
| "wasm"
Expand Down
57 changes: 55 additions & 2 deletions docs/runtime/file-types.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: "File types and loaders supported by Bun's bundler and runtime"

The Bun bundler implements a set of default loaders. As a rule of thumb, the bundler and the runtime support the same set of file types.

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

Bun uses the file extension to pick the built-in _loader_ that parses the file. Every loader has a name, such as `js`, `tsx`, or `json`. These names are used when building [plugins](/bundler/plugins) that extend Bun with custom loaders.

Expand Down Expand Up @@ -297,7 +297,7 @@ export default {

### `text`

**Text loader**. Default for `.txt`.
**Text loader**. Default for `.txt` and `.text`.

Text files can be directly imported. The file is read and returned as a string.

Expand Down Expand Up @@ -331,6 +331,59 @@ export default "Hello, world!";

</CodeGroup>

### `md`

**Markdown loader**. Default for `.md` and `.markdown`.

Markdown files can be directly imported. Bun renders them to HTML with [`Bun.markdown`](/runtime/markdown), and the import resolves to the rendered HTML as a string.

```ts
import html from "./README.md";
console.log(html); // => "<h1>My project</h1>\n..."

// via import attribute:
import notes from "./notes.txt" with { type: "md" };
```

<Note>

`bun-types` does not declare a `*.md` module, because frameworks such as Astro declare their own `*.md` module and a second declaration would override their default export. To type the import in a plain Bun project, add a `.d.ts` file with the following, plus the same block for `"*.markdown"` if you use that extension:

```ts
declare module "*.md" {
const html: string;
export default html;
}
```

</Note>

During bundling, the rendered HTML is inlined into the bundle as a string.

```ts
var README_default = `<h1>My project</h1>
<p>Some <strong>bold</strong> text.</p>
`;
```

If a `.md` file is passed as an entrypoint, it is converted to a `.js` module that `export default`s the rendered HTML.

<CodeGroup>

```md Input
# Hello

Some **bold** text.
```

```ts Output
export default `<h1>Hello</h1>
<p>Some <strong>bold</strong> text.</p>
`;
```

</CodeGroup>

### `napi`

**Native addon loader**. Default for `.node`.
Expand Down
3 changes: 3 additions & 0 deletions docs/runtime/plugins.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,11 @@ type Loader =
| "tsx"
| "json"
| "jsonc"
| "json5"
| "toml"
| "yaml"
| "xml"
| "md"
| "file"
| "napi"
| "wasm"
Expand Down
2 changes: 2 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5559,9 +5559,11 @@ declare module "bun" {
| "tsx"
| "json"
| "jsonc"
| "json5"
| "toml"
| "yaml"
| "xml"
| "md"
Comment thread
robobun marked this conversation as resolved.
Resolved
| "file"
| "napi"
| "wasm"
Expand Down
31 changes: 31 additions & 0 deletions test/integration/bun-types/bun-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,37 @@ describe("@types/bun integration test", () => {
});
});

describe("Loader", () => {
// fixture/loader.ts is also part of the typeTest runs, which debug builds skip; spawning tsc
// over just that file is cheap enough to run everywhere.
test("json5 and md are members of the union", async () => {
const checkDir = join(TEMP_DIR, "loader-check");
const tsconfig = structuredClone(sourceTsconfig);
tsconfig.include = ["loader.ts", "utilities.ts"];
tsconfig.compilerOptions.typeRoots = [join(BASE_FIXTURE_DIR, "node_modules", "@types")];
await mkdir(checkDir, { recursive: true });
await makeTree(checkDir, {
"tsconfig.json": JSON.stringify(tsconfig, null, 2),
"loader.ts": readFileSync(join(FIXTURE_SOURCE_DIR, "loader.ts"), "utf8"),
"utilities.ts": readFileSync(join(FIXTURE_SOURCE_DIR, "utilities.ts"), "utf8"),
});

await using proc = Bun.spawn({
cmd: [bunExe(), join(BASE_FIXTURE_DIR, "node_modules", "typescript", "bin", "tsc"), "-p", "."],
env: bunEnv,
cwd: checkDir,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stderr.trim()).toBe("");
expect(stdout.trim()).toBe("");
expect(exitCode).toBe(0);
});
});

describe("Test Globals", () => {
const code = `
const test_shouldBeAFunction: Function = test;
Expand Down
65 changes: 65 additions & 0 deletions test/integration/bun-types/fixture/loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type { Loader } from "bun";
// Deliberately no `declare module` for "*.md" or "*.markdown" in extensions.d.ts: frameworks declare
// both themselves (astro/client.d.ts gives them a component default export), and a bun-types
// `export =` declaration merged into theirs silently turns their default export into a string.
// Projects that want the md loader's imports typed declare the modules themselves; here both imports
// fail to resolve and stay untyped.
// @ts-expect-error
import markdown from "./README.markdown";
// @ts-expect-error
import html from "./README.md";
import { expectAssignable, expectType } from "./utilities";

// The bundler implements json5 and md and accepts them by name (`bun build --loader`,
// `Bun.build({ loader })`, plugin onLoad results), so they are members of the union.
expectAssignable<Loader>("json5");
expectAssignable<Bun.Loader>("md");
// @ts-expect-error
expectAssignable<Loader>("bogus");

expectType(html).is<any>();
expectType(markdown).is<any>();

Bun.build({
entrypoints: ["hey"],
loader: {
".json5": "json5",
".md": "md",
},
});

Bun.build({
entrypoints: ["hey"],
plugins: [
{
name: "loader-names",
setup(build) {
build.onLoad({ filter: /\.(json5|md)$/ }, args => {
// `args.loader` is the default loader for the file, so it is "json5" or "md" here;
// comparing against a name missing from the union is a no-overlap error.
if (args.loader === "json5") {
return { contents: "{ a: 1, }", loader: "json5" };
}

return { contents: "# heading", loader: "md" };
});

build.onEnd(result => {
for (const output of result.outputs) {
if (output.loader === "json5" || output.loader === "md") {
expectType(output).is<Bun.BuildArtifact>();
}
}
});
},
},
],
});

// Runtime plugins return the same OnLoadResult.
Bun.plugin({
name: "markdown",
setup(build) {
build.onLoad({ filter: /\.md$/ }, () => ({ contents: "# heading", loader: "md" }));
},
});