bun-types 1.1.37-canary.20241124T140524 → 1.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/docs/api/binary-data.md +1028 -0
  2. package/docs/api/cc.md +197 -0
  3. package/docs/api/color.md +262 -0
  4. package/docs/api/console.md +38 -0
  5. package/docs/api/dns.md +113 -0
  6. package/docs/api/fetch.md +308 -0
  7. package/docs/api/ffi.md +536 -0
  8. package/docs/api/file-io.md +358 -0
  9. package/docs/api/file-system-router.md +112 -0
  10. package/docs/api/file.md +19 -0
  11. package/docs/api/glob.md +157 -0
  12. package/docs/api/globals.md +387 -0
  13. package/docs/api/hashing.md +314 -0
  14. package/docs/api/html-rewriter.md +31 -0
  15. package/docs/api/http.md +661 -0
  16. package/docs/api/import-meta.md +69 -0
  17. package/docs/api/node-api.md +16 -0
  18. package/docs/api/semver.md +52 -0
  19. package/docs/api/spawn.md +441 -0
  20. package/docs/api/sqlite.md +692 -0
  21. package/docs/api/streams.md +214 -0
  22. package/docs/api/tcp.md +221 -0
  23. package/docs/api/test.md +1 -0
  24. package/docs/api/transpiler.md +274 -0
  25. package/docs/api/udp.md +125 -0
  26. package/docs/api/utils.md +773 -0
  27. package/docs/api/websockets.md +547 -0
  28. package/docs/api/workers.md +230 -0
  29. package/docs/benchmarks.md +120 -0
  30. package/docs/bun-flavored-toml.md +42 -0
  31. package/docs/bundler/executables.md +291 -0
  32. package/docs/bundler/index.md +1543 -0
  33. package/docs/bundler/intro.md +75 -0
  34. package/docs/bundler/loaders.md +288 -0
  35. package/docs/bundler/macros.md +327 -0
  36. package/docs/bundler/plugins.md +30 -0
  37. package/docs/bundler/vs-esbuild.md +1127 -0
  38. package/docs/cli/add.md +163 -0
  39. package/docs/cli/bun-completions.md +3 -0
  40. package/docs/cli/bun-create.md +254 -0
  41. package/docs/cli/bun-dev.md +21 -0
  42. package/docs/cli/bun-install.md +255 -0
  43. package/docs/cli/bun-upgrade.md +39 -0
  44. package/docs/cli/bunx.md +80 -0
  45. package/docs/cli/filter.md +57 -0
  46. package/docs/cli/init.md +40 -0
  47. package/docs/cli/install.md +205 -0
  48. package/docs/cli/link.md +38 -0
  49. package/docs/cli/outdated.md +61 -0
  50. package/docs/cli/patch-commit.md +9 -0
  51. package/docs/cli/pm.md +150 -0
  52. package/docs/cli/publish.md +107 -0
  53. package/docs/cli/remove.md +5 -0
  54. package/docs/cli/run.md +196 -0
  55. package/docs/cli/test.md +247 -0
  56. package/docs/cli/unlink.md +7 -0
  57. package/docs/cli/update.md +34 -0
  58. package/docs/contributing/upgrading-webkit.md +57 -0
  59. package/docs/ecosystem/elysia.md +24 -0
  60. package/docs/ecosystem/express.md +37 -0
  61. package/docs/ecosystem/hono.md +18 -0
  62. package/docs/ecosystem/react.md +65 -0
  63. package/docs/ecosystem/stric.md +37 -0
  64. package/docs/guides/binary/arraybuffer-to-array.md +27 -0
  65. package/docs/guides/binary/arraybuffer-to-blob.md +24 -0
  66. package/docs/guides/binary/arraybuffer-to-buffer.md +25 -0
  67. package/docs/guides/binary/arraybuffer-to-string.md +15 -0
  68. package/docs/guides/binary/arraybuffer-to-typedarray.md +39 -0
  69. package/docs/guides/binary/blob-to-arraybuffer.md +14 -0
  70. package/docs/guides/binary/blob-to-dataview.md +14 -0
  71. package/docs/guides/binary/blob-to-stream.md +14 -0
  72. package/docs/guides/binary/blob-to-string.md +15 -0
  73. package/docs/guides/binary/blob-to-typedarray.md +14 -0
  74. package/docs/guides/binary/buffer-to-arraybuffer.md +14 -0
  75. package/docs/guides/binary/buffer-to-blob.md +14 -0
  76. package/docs/guides/binary/buffer-to-readablestream.md +41 -0
  77. package/docs/guides/binary/buffer-to-string.md +25 -0
  78. package/docs/guides/binary/buffer-to-typedarray.md +14 -0
  79. package/docs/guides/binary/dataview-to-string.md +15 -0
  80. package/docs/guides/binary/typedarray-to-arraybuffer.md +25 -0
  81. package/docs/guides/binary/typedarray-to-blob.md +16 -0
  82. package/docs/guides/binary/typedarray-to-buffer.md +14 -0
  83. package/docs/guides/binary/typedarray-to-dataview.md +14 -0
  84. package/docs/guides/binary/typedarray-to-readablestream.md +41 -0
  85. package/docs/guides/binary/typedarray-to-string.md +16 -0
  86. package/docs/guides/ecosystem/astro.md +72 -0
  87. package/docs/guides/ecosystem/discordjs.md +77 -0
  88. package/docs/guides/ecosystem/docker.md +140 -0
  89. package/docs/guides/ecosystem/drizzle.md +185 -0
  90. package/docs/guides/ecosystem/edgedb.md +228 -0
  91. package/docs/guides/ecosystem/elysia.md +31 -0
  92. package/docs/guides/ecosystem/express.md +40 -0
  93. package/docs/guides/ecosystem/hono.md +39 -0
  94. package/docs/guides/ecosystem/mongoose.md +87 -0
  95. package/docs/guides/ecosystem/neon-drizzle.md +220 -0
  96. package/docs/guides/ecosystem/neon-serverless-postgres.md +55 -0
  97. package/docs/guides/ecosystem/nextjs.md +38 -0
  98. package/docs/guides/ecosystem/nuxt.md +56 -0
  99. package/docs/guides/ecosystem/pm2.md +57 -0
  100. package/docs/guides/ecosystem/prisma.md +140 -0
  101. package/docs/guides/ecosystem/qwik.md +107 -0
  102. package/docs/guides/ecosystem/react.md +49 -0
  103. package/docs/guides/ecosystem/remix.md +78 -0
  104. package/docs/guides/ecosystem/render.md +79 -0
  105. package/docs/guides/ecosystem/sentry.md +52 -0
  106. package/docs/guides/ecosystem/solidstart.md +58 -0
  107. package/docs/guides/ecosystem/ssr-react.md +51 -0
  108. package/docs/guides/ecosystem/stric.md +55 -0
  109. package/docs/guides/ecosystem/sveltekit.md +125 -0
  110. package/docs/guides/ecosystem/systemd.md +113 -0
  111. package/docs/guides/ecosystem/vite.md +70 -0
  112. package/docs/guides/http/cluster.md +66 -0
  113. package/docs/guides/http/fetch-unix.md +33 -0
  114. package/docs/guides/http/fetch.md +24 -0
  115. package/docs/guides/http/file-uploads.md +94 -0
  116. package/docs/guides/http/hot.md +22 -0
  117. package/docs/guides/http/proxy.md +24 -0
  118. package/docs/guides/http/server.md +46 -0
  119. package/docs/guides/http/simple.md +18 -0
  120. package/docs/guides/http/stream-file.md +48 -0
  121. package/docs/guides/http/stream-iterator.md +47 -0
  122. package/docs/guides/http/stream-node-streams-in-bun.md +20 -0
  123. package/docs/guides/http/tls.md +30 -0
  124. package/docs/guides/install/add-dev.md +26 -0
  125. package/docs/guides/install/add-git.md +36 -0
  126. package/docs/guides/install/add-optional.md +25 -0
  127. package/docs/guides/install/add-peer.md +17 -0
  128. package/docs/guides/install/add-tarball.md +33 -0
  129. package/docs/guides/install/add.md +42 -0
  130. package/docs/guides/install/azure-artifacts.md +73 -0
  131. package/docs/guides/install/cicd.md +41 -0
  132. package/docs/guides/install/custom-registry.md +30 -0
  133. package/docs/guides/install/from-npm-install-to-bun-install.md +214 -0
  134. package/docs/guides/install/git-diff-bun-lockfile.md +38 -0
  135. package/docs/guides/install/jfrog-artifactory.md +28 -0
  136. package/docs/guides/install/npm-alias.md +23 -0
  137. package/docs/guides/install/registry-scope.md +36 -0
  138. package/docs/guides/install/trusted.md +48 -0
  139. package/docs/guides/install/workspaces.md +70 -0
  140. package/docs/guides/install/yarnlock.md +42 -0
  141. package/docs/guides/process/argv.md +57 -0
  142. package/docs/guides/process/ctrl-c.md +16 -0
  143. package/docs/guides/process/ipc.md +66 -0
  144. package/docs/guides/process/nanoseconds.md +13 -0
  145. package/docs/guides/process/os-signals.md +39 -0
  146. package/docs/guides/process/spawn-stderr.md +31 -0
  147. package/docs/guides/process/spawn-stdout.md +26 -0
  148. package/docs/guides/process/spawn.md +41 -0
  149. package/docs/guides/process/stdin.md +54 -0
  150. package/docs/guides/read-file/arraybuffer.md +28 -0
  151. package/docs/guides/read-file/buffer.md +19 -0
  152. package/docs/guides/read-file/exists.md +16 -0
  153. package/docs/guides/read-file/json.md +17 -0
  154. package/docs/guides/read-file/mime.md +20 -0
  155. package/docs/guides/read-file/stream.md +26 -0
  156. package/docs/guides/read-file/string.md +22 -0
  157. package/docs/guides/read-file/uint8array.md +21 -0
  158. package/docs/guides/read-file/watch.md +68 -0
  159. package/docs/guides/runtime/cicd.md +43 -0
  160. package/docs/guides/runtime/define-constant.md +145 -0
  161. package/docs/guides/runtime/import-html.md +15 -0
  162. package/docs/guides/runtime/import-json.md +44 -0
  163. package/docs/guides/runtime/import-toml.md +30 -0
  164. package/docs/guides/runtime/read-env.md +32 -0
  165. package/docs/guides/runtime/set-env.md +37 -0
  166. package/docs/guides/runtime/shell.md +40 -0
  167. package/docs/guides/runtime/timezone.md +35 -0
  168. package/docs/guides/runtime/tsconfig-paths.md +29 -0
  169. package/docs/guides/runtime/typescript.md +47 -0
  170. package/docs/guides/runtime/vscode-debugger.md +47 -0
  171. package/docs/guides/runtime/web-debugger.md +82 -0
  172. package/docs/guides/streams/node-readable-to-arraybuffer.md +11 -0
  173. package/docs/guides/streams/node-readable-to-blob.md +11 -0
  174. package/docs/guides/streams/node-readable-to-json.md +12 -0
  175. package/docs/guides/streams/node-readable-to-string.md +12 -0
  176. package/docs/guides/streams/node-readable-to-uint8array.md +11 -0
  177. package/docs/guides/streams/to-array.md +14 -0
  178. package/docs/guides/streams/to-arraybuffer.md +14 -0
  179. package/docs/guides/streams/to-blob.md +14 -0
  180. package/docs/guides/streams/to-buffer.md +15 -0
  181. package/docs/guides/streams/to-json.md +14 -0
  182. package/docs/guides/streams/to-string.md +14 -0
  183. package/docs/guides/streams/to-typedarray.md +22 -0
  184. package/docs/guides/test/bail.md +22 -0
  185. package/docs/guides/test/coverage-threshold.md +60 -0
  186. package/docs/guides/test/coverage.md +44 -0
  187. package/docs/guides/test/happy-dom.md +68 -0
  188. package/docs/guides/test/migrate-from-jest.md +110 -0
  189. package/docs/guides/test/mock-clock.md +48 -0
  190. package/docs/guides/test/mock-functions.md +68 -0
  191. package/docs/guides/test/rerun-each.md +14 -0
  192. package/docs/guides/test/run-tests.md +111 -0
  193. package/docs/guides/test/skip-tests.md +39 -0
  194. package/docs/guides/test/snapshot.md +99 -0
  195. package/docs/guides/test/spy-on.md +46 -0
  196. package/docs/guides/test/testing-library.md +87 -0
  197. package/docs/guides/test/timeout.md +15 -0
  198. package/docs/guides/test/todo-tests.md +67 -0
  199. package/docs/guides/test/update-snapshots.md +50 -0
  200. package/docs/guides/test/watch-mode.md +19 -0
  201. package/docs/guides/util/base64.md +15 -0
  202. package/docs/guides/util/deep-equals.md +39 -0
  203. package/docs/guides/util/deflate.md +18 -0
  204. package/docs/guides/util/detect-bun.md +23 -0
  205. package/docs/guides/util/entrypoint.md +17 -0
  206. package/docs/guides/util/escape-html.md +22 -0
  207. package/docs/guides/util/file-url-to-path.md +14 -0
  208. package/docs/guides/util/gzip.md +18 -0
  209. package/docs/guides/util/hash-a-password.md +54 -0
  210. package/docs/guides/util/import-meta-dir.md +13 -0
  211. package/docs/guides/util/import-meta-file.md +13 -0
  212. package/docs/guides/util/import-meta-path.md +13 -0
  213. package/docs/guides/util/main.md +32 -0
  214. package/docs/guides/util/path-to-file-url.md +14 -0
  215. package/docs/guides/util/sleep.md +22 -0
  216. package/docs/guides/util/version.md +21 -0
  217. package/docs/guides/util/which-path-to-executable-bin.md +15 -0
  218. package/docs/guides/websocket/compression.md +31 -0
  219. package/docs/guides/websocket/context.md +72 -0
  220. package/docs/guides/websocket/pubsub.md +38 -0
  221. package/docs/guides/websocket/simple.md +33 -0
  222. package/docs/guides/write-file/append.md +52 -0
  223. package/docs/guides/write-file/basic.md +44 -0
  224. package/docs/guides/write-file/blob.md +28 -0
  225. package/docs/guides/write-file/cat.md +17 -0
  226. package/docs/guides/write-file/file-cp.md +16 -0
  227. package/docs/guides/write-file/filesink.md +52 -0
  228. package/docs/guides/write-file/response.md +17 -0
  229. package/docs/guides/write-file/stdout.md +21 -0
  230. package/docs/guides/write-file/stream.md +17 -0
  231. package/docs/guides/write-file/unlink.md +23 -0
  232. package/docs/index.md +77 -0
  233. package/docs/install/cache.md +57 -0
  234. package/docs/install/index.md +202 -0
  235. package/docs/install/lifecycle.md +46 -0
  236. package/docs/install/lockfile.md +90 -0
  237. package/docs/install/npmrc.md +75 -0
  238. package/docs/install/overrides.md +73 -0
  239. package/docs/install/patch.md +57 -0
  240. package/docs/install/registries.md +30 -0
  241. package/docs/install/workspaces.md +70 -0
  242. package/docs/installation.md +289 -0
  243. package/docs/project/benchmarking.md +203 -0
  244. package/docs/project/building-windows.md +162 -0
  245. package/docs/project/internals/build-process-for-ci.md +75 -0
  246. package/docs/project/roadmap.md +87 -0
  247. package/docs/quickstart.md +144 -0
  248. package/docs/runtime/autoimport.md +94 -0
  249. package/docs/runtime/bun-apis.md +129 -0
  250. package/docs/runtime/bunfig.md +532 -0
  251. package/docs/runtime/debugger.md +325 -0
  252. package/docs/runtime/env.md +214 -0
  253. package/docs/runtime/hot.md +139 -0
  254. package/docs/runtime/index.md +309 -0
  255. package/docs/runtime/jsx.md +326 -0
  256. package/docs/runtime/loaders.md +127 -0
  257. package/docs/runtime/modules.md +298 -0
  258. package/docs/runtime/nodejs-apis.md +456 -0
  259. package/docs/runtime/plugins.md +605 -0
  260. package/docs/runtime/shell.md +537 -0
  261. package/docs/runtime/typescript.md +60 -0
  262. package/docs/runtime/web-apis.md +128 -0
  263. package/docs/test/coverage.md +91 -0
  264. package/docs/test/dom.md +75 -0
  265. package/docs/test/hot.md +15 -0
  266. package/docs/test/lifecycle.md +81 -0
  267. package/docs/test/mocks.md +236 -0
  268. package/docs/test/snapshots.md +15 -0
  269. package/docs/test/time.md +106 -0
  270. package/docs/test/writing.md +547 -0
  271. package/docs/typescript.md +51 -0
  272. package/package.json +5 -4
@@ -0,0 +1,75 @@
1
+ <!-- This document is a work in progress. It's not currently included in the actual docs. -->
2
+
3
+ The goal of this document is to break down why bundling is necessary, how it works, and how the bundler became such a key part of modern JavaScript development. The content is not specific to Bun's bundler, but is rather aimed at anyone looking for a greater understanding of how bundlers work and, by extension, how most modern frameworks are implemented.
4
+
5
+ ## What is bundling
6
+
7
+ With the adoption of ECMAScript modules (ESM), browsers can now resolve `import`/`export` statements in JavaScript files loaded via `<script>` tags.
8
+
9
+ {% codetabs %}
10
+
11
+ ```html#index.html
12
+ <html>
13
+ <head>
14
+ <script type="module" src="/index.js" ></script>
15
+ </head>
16
+ </html>
17
+ ```
18
+
19
+ ```js#index.js
20
+ import {sayHello} from "./hello.js";
21
+
22
+ sayHello();
23
+ ```
24
+
25
+ ```js#hello.js
26
+ export function sayHello() {
27
+ console.log("Hello, world!");
28
+ }
29
+ ```
30
+
31
+ {% /codetabs %}
32
+
33
+ When a user visits this website, the files are loaded in the following order:
34
+
35
+ {% image src="/images/module_loading_unbundled.png" /%}
36
+
37
+ {% callout %}
38
+ **Relative imports** — Relative imports are resolved relative to the URL of the importing file. Because we're importing `./hello.js` from `/index.js`, the browser resolves it to `/hello.js`. If instead we'd imported `./hello.js` from `/src/index.js`, the browser would have resolved it to `/src/hello.js`.
39
+ {% /callout %}
40
+
41
+ This approach works, it requires three round-trip HTTP requests before the browser is ready to render the page. On slow internet connections, this may add up to a non-trivial delay.
42
+
43
+ This example is extremely simplistic. A modern app may be loading dozens of modules from `node_modules`, each consisting of hundred of files. Loading each of these files with a separate HTTP request becomes untenable very quickly. While most of these requests will be running in parallel, the number of round-trip requests can still be very high; plus, there are limits on how many simultaneous requests a browser can make.
44
+
45
+ {% callout %}
46
+ Some recent advances like modulepreload and HTTP/3 are intended to solve some of these problems, but at the moment bundling is still the most performant approach.
47
+ {% /callout %}
48
+
49
+ The answer: bundling.
50
+
51
+ ## Entrypoints
52
+
53
+ A bundler accepts an "entrypoint" to your source code (in this case, `/index.js`) and outputs a single file containing all of the code needed to run your app. If does so by parsing your source code, reading the `import`/`export` statements, and building a "module graph" of your app's dependencies.
54
+
55
+ {% image src="/images/bundling.png" /%}
56
+
57
+ We can now load `/bundle.js` from our `index.html` file and eliminate a round trip request, decreasing load times for our app.
58
+
59
+ {% image src="/images/module_loading_bundled.png" /%}
60
+
61
+ ## Loaders
62
+
63
+ Bundlers typically have some set of built-in "loaders".
64
+
65
+ ## Transpilation
66
+
67
+ The JavaScript files above are just that: plain JavaScript. They can be directly executed by any modern browser.
68
+
69
+ But modern tooling goes far beyond HTML, JavaScript, and CSS. JSX, TypeScript, and PostCSS/CSS-in-JS are all popular technologies that involve non-standard syntax that must be converted into vanilla JavaScript and CSS before if can be consumed by a browser.
70
+
71
+ ## Chunking
72
+
73
+ ## Module resolution
74
+
75
+ ## Plugins
@@ -0,0 +1,288 @@
1
+ The Bun bundler implements a set of default loaders out of the box. As a rule of thumb, the bundler and the runtime both support the same set of file types out of the box.
2
+
3
+ `.js` `.cjs` `.mjs` `.mts` `.cts` `.ts` `.tsx` `.jsx` `.toml` `.json` `.txt` `.wasm` `.node`
4
+
5
+ Bun uses the file extension to determine which built-in _loader_ should be used to parse the file. Every loader has a name, such as `js`, `tsx`, or `json`. These names are used when building [plugins](https://bun.sh/docs/bundler/plugins) that extend Bun with custom loaders.
6
+
7
+ ## Built-in loaders
8
+
9
+ ### `js`
10
+
11
+ **JavaScript**. Default for `.cjs` and `.mjs`.
12
+
13
+ Parses the code and applies a set of default transforms like dead-code elimination and tree shaking. Note that Bun does not attempt to down-convert syntax at the moment.
14
+
15
+ ### `jsx`
16
+
17
+ **JavaScript + JSX.**. Default for `.js` and `.jsx`.
18
+
19
+ Same as the `js` loader, but JSX syntax is supported. By default, JSX is down-converted to plain JavaScript; the details of how this is done depends on the `jsx*` compiler options in your `tsconfig.json`. Refer to the TypeScript documentation [on JSX](https://www.typescriptlang.org/docs/handbook/jsx.html) for more information.
20
+
21
+ ### `ts`
22
+
23
+ **TypeScript loader**. Default for `.ts`, `.mts`, and `.cts`.
24
+
25
+ Strips out all TypeScript syntax, then behaves identically to the `js` loader. Bun does not perform typechecking.
26
+
27
+ ### `tsx`
28
+
29
+ **TypeScript + JSX loader**. Default for `.tsx`. Transpiles both TypeScript and JSX to vanilla JavaScript.
30
+
31
+ ### `json`
32
+
33
+ **JSON loader**. Default for `.json`.
34
+
35
+ JSON files can be directly imported.
36
+
37
+ ```ts
38
+ import pkg from "./package.json";
39
+ pkg.name; // => "my-package"
40
+ ```
41
+
42
+ During bundling, the parsed JSON is inlined into the bundle as a JavaScript object.
43
+
44
+ ```ts
45
+ var pkg = {
46
+ name: "my-package",
47
+ // ... other fields
48
+ };
49
+ pkg.name;
50
+ ```
51
+
52
+ If a `.json` file is passed as an entrypoint to the bundler, it will be converted to a `.js` module that `export default`s the parsed object.
53
+
54
+ {% codetabs %}
55
+
56
+ ```json#Input
57
+ {
58
+ "name": "John Doe",
59
+ "age": 35,
60
+ "email": "johndoe@example.com"
61
+ }
62
+ ```
63
+
64
+ ```js#Output
65
+ export default {
66
+ name: "John Doe",
67
+ age: 35,
68
+ email: "johndoe@example.com"
69
+ }
70
+ ```
71
+
72
+ {% /codetabs %}
73
+
74
+ ### `toml`
75
+
76
+ **TOML loader**. Default for `.toml`.
77
+
78
+ TOML files can be directly imported. Bun will parse them with its fast native TOML parser.
79
+
80
+ ```ts
81
+ import config from "./bunfig.toml";
82
+ config.logLevel; // => "debug"
83
+
84
+ // via import attribute:
85
+ // import myCustomTOML from './my.config' with {type: "toml"};
86
+ ```
87
+
88
+ During bundling, the parsed TOML is inlined into the bundle as a JavaScript object.
89
+
90
+ ```ts
91
+ var config = {
92
+ logLevel: "debug",
93
+ // ...other fields
94
+ };
95
+ config.logLevel;
96
+ ```
97
+
98
+ If a `.toml` file is passed as an entrypoint, it will be converted to a `.js` module that `export default`s the parsed object.
99
+
100
+ {% codetabs %}
101
+
102
+ ```toml#Input
103
+ name = "John Doe"
104
+ age = 35
105
+ email = "johndoe@example.com"
106
+ ```
107
+
108
+ ```js#Output
109
+ export default {
110
+ name: "John Doe",
111
+ age: 35,
112
+ email: "johndoe@example.com"
113
+ }
114
+ ```
115
+
116
+ {% /codetabs %}
117
+
118
+ ### `text`
119
+
120
+ **Text loader**. Default for `.txt`.
121
+
122
+ The contents of the text file are read and inlined into the bundle as a string.
123
+ Text files can be directly imported. The file is read and returned as a string.
124
+
125
+ ```ts
126
+ import contents from "./file.txt";
127
+ console.log(contents); // => "Hello, world!"
128
+
129
+ // To import an html file as text
130
+ // The "type' attribute can be used to override the default loader.
131
+ import html from "./index.html" with { type: "text" };
132
+ ```
133
+
134
+ When referenced during a build, the contents are into the bundle as a string.
135
+
136
+ ```ts
137
+ var contents = `Hello, world!`;
138
+ console.log(contents);
139
+ ```
140
+
141
+ If a `.txt` file is passed as an entrypoint, it will be converted to a `.js` module that `export default`s the file contents.
142
+
143
+ {% codetabs %}
144
+
145
+ ```txt#Input
146
+ Hello, world!
147
+ ```
148
+
149
+ ```js#Output
150
+ export default "Hello, world!";
151
+ ```
152
+
153
+ {% /codetabs %}
154
+
155
+ ### `wasm`
156
+
157
+ **WebAssembly loader**. Default for `.wasm`.
158
+
159
+ In the runtime, WebAssembly files can be directly imported. The file is read and returned as a `WebAssembly.Module`.
160
+
161
+ ```ts
162
+ import wasm from "./module.wasm";
163
+ console.log(wasm); // => WebAssembly.Module
164
+ ```
165
+
166
+ In the bundler, `.wasm` files are handled using the [`file`](#file) loader.
167
+
168
+ ### `napi`
169
+
170
+ **Native addon loader**. Default for `.node`.
171
+
172
+ In the runtime, native addons can be directly imported.
173
+
174
+ ```ts
175
+ import addon from "./addon.node";
176
+ console.log(addon);
177
+ ```
178
+
179
+ In the bundler, `.node` files are handled using the [`file`](#file) loader.
180
+
181
+ ### `sqlite`
182
+
183
+ **SQLite loader**. `with { "type": "sqlite" }` import attribute
184
+
185
+ In the runtime and bundler, SQLite databases can be directly imported. This will load the database using [`bun:sqlite`](https://bun.sh/docs/api/sqlite).
186
+
187
+ ```ts
188
+ import db from "./my.db" with { type: "sqlite" };
189
+ ```
190
+
191
+ This is only supported when the `target` is `bun`.
192
+
193
+ By default, the database is external to the bundle (so that you can potentially use a database loaded elsewhere), so the database file on-disk won't be bundled into the final output.
194
+
195
+ You can change this behavior with the `"embed"` attribute:
196
+
197
+ ```ts
198
+ // embed the database into the bundle
199
+ import db from "./my.db" with { type: "sqlite", embed: "true" };
200
+ ```
201
+
202
+ When using a [standalone executable](https://bun.sh/docs/bundler/executables), the database is embedded into the single-file executable.
203
+
204
+ Otherwise, the database to embed is copied into the `outdir` with a hashed filename.
205
+
206
+ ### `sh` loader
207
+
208
+ **Bun Shell loader**. Default for `.sh` files
209
+
210
+ This loader is used to parse [Bun Shell](https://bun.sh/docs/runtime/shell) scripts. It's only supported when starting Bun itself, so it's not available in the bundler or in the runtime.
211
+
212
+ ```sh
213
+ $ bun run ./script.sh
214
+ ```
215
+
216
+ ### `file`
217
+
218
+ **File loader**. Default for all unrecognized file types.
219
+
220
+ The file loader resolves the import as a _path/URL_ to the imported file. It's commonly used for referencing media or font assets.
221
+
222
+ ```ts#logo.ts
223
+ import logo from "./logo.svg";
224
+ console.log(logo);
225
+ ```
226
+
227
+ _In the runtime_, Bun checks that the `logo.svg` file exists and converts it to an absolute path to the location of `logo.svg` on disk.
228
+
229
+ ```bash
230
+ $ bun run logo.ts
231
+ /path/to/project/logo.svg
232
+ ```
233
+
234
+ _In the bundler_, things are slightly different. The file is copied into `outdir` as-is, and the import is resolved as a relative path pointing to the copied file.
235
+
236
+ ```ts#Output
237
+ var logo = "./logo.svg";
238
+ console.log(logo);
239
+ ```
240
+
241
+ If a value is specified for `publicPath`, the import will use value as a prefix to construct an absolute path/URL.
242
+
243
+ {% table %}
244
+
245
+ - Public path
246
+ - Resolved import
247
+
248
+ ---
249
+
250
+ - `""` (default)
251
+ - `/logo.svg`
252
+
253
+ ---
254
+
255
+ - `"/assets"`
256
+ - `/assets/logo.svg`
257
+
258
+ ---
259
+
260
+ - `"https://cdn.example.com/"`
261
+ - `https://cdn.example.com/logo.svg`
262
+
263
+ {% /table %}
264
+
265
+ {% callout %}
266
+ The location and file name of the copied file is determined by the value of [`naming.asset`](https://bun.sh/docs/bundler#naming).
267
+ {% /callout %}
268
+ This loader is copied into the `outdir` as-is. The name of the copied file is determined using the value of `naming.asset`.
269
+
270
+ {% details summary="Fixing TypeScript import errors" %}
271
+ If you're using TypeScript, you may get an error like this:
272
+
273
+ ```ts
274
+ // TypeScript error
275
+ // Cannot find module './logo.svg' or its corresponding type declarations.
276
+ ```
277
+
278
+ This can be fixed by creating `*.d.ts` file anywhere in your project (any name will work) with the following contents:
279
+
280
+ ```ts
281
+ declare module "*.svg" {
282
+ const content: string;
283
+ export default content;
284
+ }
285
+ ```
286
+
287
+ This tells TypeScript that any default imports from `.svg` should be treated as a string.
288
+ {% /details %}
@@ -0,0 +1,327 @@
1
+ Macros are a mechanism for running JavaScript functions _at bundle-time_. The value returned from these functions are directly inlined into your bundle.
2
+
3
+ <!-- embed the result in your (browser) bundle. This is useful for things like embedding the current Git commit hash in your code, making fetch requests to your API at build-time, dead code elimination, and more. -->
4
+
5
+ As a toy example, consider this simple function that returns a random number.
6
+
7
+ ```ts
8
+ export function random() {
9
+ return Math.random();
10
+ }
11
+ ```
12
+
13
+ This is just a regular function in a regular file, but we can use it as a macro like so:
14
+
15
+ ```ts#cli.tsx
16
+ import { random } from './random.ts' with { type: 'macro' };
17
+
18
+ console.log(`Your random number is ${random()}`);
19
+ ```
20
+
21
+ {% callout %}
22
+ **Note** — Macros are indicated using [_import attribute_](https://github.com/tc39/proposal-import-attributes) syntax. If you haven't seen this syntax before, it's a Stage 3 TC39 proposal that lets you attach additional metadata to `import` statements.
23
+ {% /callout %}
24
+
25
+ Now we'll bundle this file with `bun build`. The bundled file will be printed to stdout.
26
+
27
+ ```bash
28
+ $ bun build ./cli.tsx
29
+ console.log(`Your random number is ${0.6805550949689833}`);
30
+ ```
31
+
32
+ As you can see, the source code of the `random` function occurs nowhere in the bundle. Instead, it is executed _during bundling_ and function call (`random()`) is replaced with the result of the function. Since the source code will never be included in the bundle, macros can safely perform privileged operations like reading from a database.
33
+
34
+ ## When to use macros
35
+
36
+ If you have several build scripts for small things where you would otherwise have a one-off build script, bundle-time code execution can be easier to maintain. It lives with the rest of your code, it runs with the rest of the build, it is automatically parallelized, and if it fails, the build fails too.
37
+
38
+ If you find yourself running a lot of code at bundle-time though, consider running a server instead.
39
+
40
+ ## Import attributes
41
+
42
+ Bun Macros are import statements annotated using either:
43
+
44
+ - `with { type: 'macro' }` — an [import attribute](https://github.com/tc39/proposal-import-attributes), a Stage 3 ECMA Scrd
45
+ - `assert { type: 'macro' }` — an import assertion, an earlier incarnation of import attributes that has now been abandoned (but is [already supported](https://caniuse.com/mdn-javascript_statements_import_import_assertions) by a number of browsers and runtimes)
46
+
47
+ ## Security considerations
48
+
49
+ Macros must explicitly be imported with `{ type: "macro" }` in order to be executed at bundle-time. These imports have no effect if they are not called, unlike regular JavaScript imports which may have side effects.
50
+
51
+ You can disable macros entirely by passing the `--no-macros` flag to Bun. It produces a build error like this:
52
+
53
+ ```js
54
+ error: Macros are disabled
55
+
56
+ foo();
57
+ ^
58
+ ./hello.js:3:1 53
59
+ ```
60
+
61
+ To reduce the potential attack surface for malicious packages, macros cannot be _invoked_ from inside `node_modules/**/*`. If a package attempts to invoke a macro, you'll see an error like this:
62
+
63
+ ```js
64
+ error: For security reasons, macros cannot be run from node_modules.
65
+
66
+ beEvil();
67
+ ^
68
+ node_modules/evil/index.js:3:1 50
69
+ ```
70
+
71
+ Your application code can still import macros from `node_modules` and invoke them.
72
+
73
+ ```ts
74
+ import {macro} from "some-package" with { type: "macro" };
75
+
76
+ macro();
77
+ ```
78
+
79
+ ## Export condition `"macro"`
80
+
81
+ When shipping a library containing a macro to `npm` or another package registry, use the `"macro"` [export condition](https://nodejs.org/api/packages.html#conditional-exports) to provide a special version of your package exclusively for the macro environment.
82
+
83
+ ```jsonc#package.json
84
+ {
85
+ "name": "my-package",
86
+ "exports": {
87
+ "import": "./index.js",
88
+ "require": "./index.js",
89
+ "default": "./index.js",
90
+ "macro": "./index.macro.js"
91
+ }
92
+ }
93
+ ```
94
+
95
+ With this configuration, users can consume your package at runtime or at bundle-time using the same import specifier:
96
+
97
+ ```ts
98
+ import pkg from "my-package"; // runtime import
99
+ import {macro} from "my-package" with { type: "macro" }; // macro import
100
+ ```
101
+
102
+ The first import will resolve to `./node_modules/my-package/index.js`, while the second will be resolved by Bun's bundler to `./node_modules/my-package/index.macro.js`.
103
+
104
+ ## Execution
105
+
106
+ When Bun's transpiler sees a macro import, it calls the function inside the transpiler using Bun's JavaScript runtime and converts the return value from JavaScript into an AST node. These JavaScript functions are called at bundle-time, not runtime.
107
+
108
+ Macros are executed synchronously in the transpiler during the visiting phase—before plugins and before the transpiler generates the AST. They are executed in the order they are imported. The transpiler will wait for the macro to finish executing before continuing. The transpiler will also `await` any `Promise` returned by a macro.
109
+
110
+ Bun's bundler is multi-threaded. As such, macros execute in parallel inside of multiple spawned JavaScript "workers".
111
+
112
+ ## Dead code elimination
113
+
114
+ The bundler performs dead code elimination _after_ running and inlining macros. So given the following macro:
115
+
116
+ ```ts#returnFalse.ts
117
+ export function returnFalse() {
118
+ return false;
119
+ }
120
+ ```
121
+
122
+ ...then bundling the following file will produce an empty bundle, provided that the minify syntax option is enabled.
123
+
124
+ ```ts
125
+ import {returnFalse} from './returnFalse.ts' with { type: 'macro' };
126
+
127
+ if (returnFalse()) {
128
+ console.log("This code is eliminated");
129
+ }
130
+ ```
131
+
132
+ ## Serializability
133
+
134
+ Bun's transpiler needs to be able to serialize the result of the macro so it can be inlined into the AST. All JSON-compatible data structures are supported:
135
+
136
+ ```ts#macro.ts
137
+ export function getObject() {
138
+ return {
139
+ foo: "bar",
140
+ baz: 123,
141
+ array: [ 1, 2, { nested: "value" }],
142
+ };
143
+ }
144
+ ```
145
+
146
+ Macros can be async, or return `Promise` instances. Bun's transpiler will automatically `await` the `Promise` and inline the result.
147
+
148
+ ```ts#macro.ts
149
+ export async function getText() {
150
+ return "async value";
151
+ }
152
+ ```
153
+
154
+ The transpiler implements special logic for serializing common data formats like `Response`, `Blob`, `TypedArray`.
155
+
156
+ - `TypedArray`: Resolves to a base64-encoded string.
157
+ - `Response`: Bun will read the `Content-Type` and serialize accordingly; for instance, a `Response` with type `application/json` will be automatically parsed into an object and `text/plain` will be inlined as a string. Responses with an unrecognized or `undefined` `type` will be base-64 encoded.
158
+ - `Blob`: As with `Response`, the serialization depends on the `type` property.
159
+
160
+ The result of `fetch` is `Promise<Response>`, so it can be directly returned.
161
+
162
+ ```ts#macro.ts
163
+ export function getObject() {
164
+ return fetch("https://bun.sh")
165
+ }
166
+ ```
167
+
168
+ Functions and instances of most classes (except those mentioned above) are not serializable.
169
+
170
+ ```ts
171
+ export function getText(url: string) {
172
+ // this doesn't work!
173
+ return () => {};
174
+ }
175
+ ```
176
+
177
+ ## Arguments
178
+
179
+ Macros can accept inputs, but only in limited cases. The value must be statically known. For example, the following is not allowed:
180
+
181
+ ```ts
182
+ import {getText} from './getText.ts' with { type: 'macro' };
183
+
184
+ export function howLong() {
185
+ // the value of `foo` cannot be statically known
186
+ const foo = Math.random() ? "foo" : "bar";
187
+
188
+ const text = getText(`https://example.com/${foo}`);
189
+ console.log("The page is ", text.length, " characters long");
190
+ }
191
+ ```
192
+
193
+ However, if the value of `foo` is known at bundle-time (say, if it's a constant or the result of another macro) then it's allowed:
194
+
195
+ ```ts
196
+ import {getText} from './getText.ts' with { type: 'macro' };
197
+ import {getFoo} from './getFoo.ts' with { type: 'macro' };
198
+
199
+ export function howLong() {
200
+ // this works because getFoo() is statically known
201
+ const foo = getFoo();
202
+ const text = getText(`https://example.com/${foo}`);
203
+ console.log("The page is", text.length, "characters long");
204
+ }
205
+ ```
206
+
207
+ This outputs:
208
+
209
+ ```ts
210
+ function howLong() {
211
+ console.log("The page is", 1322, "characters long");
212
+ }
213
+ export { howLong };
214
+ ```
215
+
216
+ ## Examples
217
+
218
+ ### Embed latest git commit hash
219
+
220
+ {% codetabs %}
221
+
222
+ ```ts#getGitCommitHash.ts
223
+ export function getGitCommitHash() {
224
+ const {stdout} = Bun.spawnSync({
225
+ cmd: ["git", "rev-parse", "HEAD"],
226
+ stdout: "pipe",
227
+ });
228
+
229
+ return stdout.toString();
230
+ }
231
+ ```
232
+
233
+ {% /codetabs %}
234
+
235
+ <!-- --target=browser so they can clearly see it's for browsers -->
236
+
237
+ When we build it, the `getGitCommitHash` is replaced with the result of calling the function:
238
+
239
+ {% codetabs %}
240
+
241
+ ```ts#input
242
+ import { getGitCommitHash } from './getGitCommitHash.ts' with { type: 'macro' };
243
+
244
+ console.log(`The current Git commit hash is ${getGitCommitHash()}`);
245
+ ```
246
+
247
+ ```bash#output
248
+ console.log(`The current Git commit hash is 3ee3259104f`);
249
+ ```
250
+
251
+ {% /codetabs %}
252
+
253
+ You're probably thinking "Why not just use `process.env.GIT_COMMIT_HASH`?" Well, you can do that too. But can you do this with an environment variable?
254
+
255
+ ### Make `fetch()` requests at bundle-time
256
+
257
+ In this example, we make an outgoing HTTP request using `fetch()`, parse the HTML response using `HTMLRewriter`, and return an object containing the title and meta tags–all at bundle-time.
258
+
259
+ ```ts
260
+ export async function extractMetaTags(url: string) {
261
+ const response = await fetch(url);
262
+ const meta = {
263
+ title: "",
264
+ };
265
+ new HTMLRewriter()
266
+ .on("title", {
267
+ text(element) {
268
+ meta.title += element.text;
269
+ },
270
+ })
271
+ .on("meta", {
272
+ element(element) {
273
+ const name =
274
+ element.getAttribute("name") || element.getAttribute("property") || element.getAttribute("itemprop");
275
+
276
+ if (name) meta[name] = element.getAttribute("content");
277
+ },
278
+ })
279
+ .transform(response);
280
+
281
+ return meta;
282
+ }
283
+ ```
284
+
285
+ <!-- --target=browser so they can clearly see it's for browsers -->
286
+
287
+ The `extractMetaTags` function is erased at bundle-time and replaced with the result of the function call. This means that the `fetch` request happens at bundle-time, and the result is embedded in the bundle. Also, the branch throwing the error is eliminated since it's unreachable.
288
+
289
+ {% codetabs %}
290
+
291
+ ```ts#input
292
+ import { extractMetaTags } from './meta.ts' with { type: 'macro' };
293
+
294
+ export const Head = () => {
295
+ const headTags = extractMetaTags("https://example.com");
296
+
297
+ if (headTags.title !== "Example Domain") {
298
+ throw new Error("Expected title to be 'Example Domain'");
299
+ }
300
+
301
+ return <head>
302
+ <title>{headTags.title}</title>
303
+ <meta name="viewport" content={headTags.viewport} />
304
+ </head>;
305
+ };
306
+ ```
307
+
308
+ ```ts#output
309
+ import { jsx, jsxs } from "react/jsx-runtime";
310
+ export const Head = () => {
311
+ jsxs("head", {
312
+ children: [
313
+ jsx("title", {
314
+ children: "Example Domain",
315
+ }),
316
+ jsx("meta", {
317
+ name: "viewport",
318
+ content: "width=device-width, initial-scale=1",
319
+ }),
320
+ ],
321
+ });
322
+ };
323
+
324
+ export { Head };
325
+ ```
326
+
327
+ {% /codetabs %}