### Test Setup Script Example Source: https://bun.com/docs/test/configuration An example `test-setup.ts` script demonstrating global test setup using `beforeAll` and cleanup using `afterAll`. This script can be preloaded before tests run. ```typescript // Global test setup import { beforeAll, afterAll } from "bun:test"; beforeAll(() => { // Set up test database setupTestDatabase(); }); afterAll(() => { // Clean up cleanupTestDatabase(); }); ``` -------------------------------- ### Install dependencies and start the Hono development server Source: https://bun.com/docs/guides/ecosystem/hono Navigate into the project directory, install the necessary dependencies using `bun install`, and then start the development server with `bun run dev`. ```shell cd myapp bun install ``` ```shell bun run dev ``` -------------------------------- ### Global package execution example Source: https://bun.com/docs/pm/cli/add Demonstrates running a globally installed command-line tool. ```txt ______ < Bun! > ------ \ ^__^ \ (oo)\л_______ (__)\ )\/\n ||----w | || || ``` -------------------------------- ### Initialize a Remix Project with Bun Source: https://bun.com/docs/guides/ecosystem/remix Use this command to start a new Remix project. Bun will handle dependency installation. ```sh bun create remix ``` -------------------------------- ### Setup and Teardown Example Source: https://bun.com/docs/test/writing-tests Demonstrates the use of `beforeEach` and `afterEach` hooks for setting up and cleaning up test environments. These hooks run before and after each test, respectively. ```typescript import { beforeEach, afterEach, test } from "bun:test"; let testUser; beforeEach(() => { testUser = createTestUser(); }); afterEach(() => { cleanupTestUser(testUser); }); test("should update user profile", () => { // Use testUser in test }); ``` -------------------------------- ### Qwik Project Creation Output Source: https://bun.com/docs/guides/ecosystem/qwik This is the interactive output from `bun create qwik`, showing the project setup process, dependency installation, and next steps. ```txt ............ .::: :--------:. .:::: .:-------:. .:::::. .:-------. ::::::. .:------. ::::::. :-----: ::::::. .:----- :::::::. .----- ::::::::.. ---:. .:::::::::. :-:. ..:::::::::::: ...:::: ┌ Let's create a Qwik App ✨ (v1.2.10) │ ◇ Where would you like to create your new project? (Use '.' or './' for current directory) │ ./my-app │ ● Creating new project in /path/to/my-app ... 🐇 │ ◇ Select a starter │ Basic App │ ◇ Would you like to install bun dependencies? │ Yes │ ◇ Initialize a new git repository? │ No │ ◇ Finishing the install. Wanna hear a joke? │ Yes │ ○ ────────────────────────────────────────────────────────╮ │ │ │ How do you know if there’s an elephant under your bed? │ │ Your head hits the ceiling! │ │ │ ├──────────────────────────────────────────────────────────╯ │ ◇ App Created 🐰 │ ◇ Installed bun dependencies 📋 │ ○ Result ─────────────────────────────────────────────╮ │ │ │ Success! Project created in my-app directory │ │ │ │ Integrations? Add Netlify, Cloudflare, Tailwind... │ │ bun qwik add │ │ │ │ Relevant docs: │ https://qwik.dev/docs/getting-started/ │ │ │ │ Questions? Start the conversation at: │ https://qwik.dev/chat │ │ https://twitter.com/QwikDev │ │ │ │ Presentations, Podcasts and Videos: │ https://qwik.dev/media/ │ │ │ │ Next steps: │ cd my-app │ │ bun start │ │ │ │ │ ├──────────────────────────────────────────────────────╯ │ └ Happy coding! 🎉 ``` -------------------------------- ### Initialize Astro Project with Bun Source: https://bun.com/docs/guides/ecosystem/astro Use `bun create astro` to start a new Astro project. Bun automatically handles dependency installation. ```sh bun create astro ``` -------------------------------- ### Example: Node modules tree structure Source: https://bun.com/docs/pm/overrides This illustrates the typical structure of the 'node_modules' directory after running 'bun install' without any overrides. It shows the installed versions of direct dependencies and their metadependencies. ```txt node_modules ├── foo@1.2.3 └── bar@4.5.6 ``` -------------------------------- ### Example: Default dependency installation without overrides Source: https://bun.com/docs/pm/overrides This shows a basic package.json without any overrides. When 'bun install' is run, Bun installs the latest versions of all dependencies and metadependencies according to their specified ranges. ```json { "name": "my-app", "dependencies": { "foo": "^2.0.0" } } ``` -------------------------------- ### SolidStart Project Creation Output Source: https://bun.com/docs/guides/ecosystem/solidstart The CLI output confirms the project name, selected template, and provides instructions to get started. ```txt ┌ Create-Solid v0.6.11 │ ◇ Project Name │ my-app │ ◇ Which template would you like to use? │ basic │ ◇ Project created 🎉 │ ◇ To get started, run: ─╮ │ │ │ cd my-app │ │ bun install │ │ bun dev │ │ │ ├────────────────────────╯ ``` -------------------------------- ### Local Template with Setup Logic Source: https://bun.com/docs/runtime/templating/create Define pre-installation, post-installation, and start scripts within the `bun-create` section of a local template's `package.json`. Supports string or array of strings for commands. ```json { "name": "@bun-examples/simplereact", "version": "0.0.1", "main": "index.js", "dependencies": { "react": "^17.0.2", "react-dom": "^17.0.2" }, "bun-create": { "preinstall": "echo 'Installing...'", "postinstall": ["echo 'Done!'"], "start": "bun run echo 'Hello world!'" } } ``` -------------------------------- ### Install Bun and Run Commands in GitHub Actions Source: https://bun.com/docs/guides/install/cicd Use the `oven-sh/setup-bun@v2` action to install Bun and then run `bun install`. ```yaml title: my-workflow jobs: my-job: title: my-job runs-on: ubuntu-latest steps: # ... - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 # [!code ++] # run any `bun` or `bunx` command - run: bun install # [!code ++] ``` -------------------------------- ### Install Dependencies Source: https://bun.com/docs/guides/ecosystem/solidstart Navigate into the project directory and install the necessary dependencies using `bun install`. ```sh cd my-app bun install ``` -------------------------------- ### Bunfig.toml Configuration Example Source: https://bun.com/docs/pm/cli/install This TOML snippet shows the default configuration options for `bun install` within `bunfig.toml`. It includes settings for dependency installation, lockfile behavior, script execution, and package age gate security. ```toml icon="settings" theme={"theme":{"light":"github-light","dark":"dracula"}} [install] # whether to install optionalDependencies optional = true # whether to install devDependencies dev = true # whether to install peerDependencies peer = true # equivalent to `--production` flag production = false # equivalent to `--save-text-lockfile` flag saveTextLockfile = false # equivalent to `--frozen-lockfile` flag frozenLockfile = false # equivalent to `--dry-run` flag dryRun = false # equivalent to `--concurrent-scripts` flag concurrentScripts = 16 # (cpu count or GOMAXPROCS) x2 # installation strategy: "hoisted" or "isolated" # default depends on lockfile configVersion and workspaces: # - configVersion = 1: "isolated" if using workspaces, otherwise "hoisted" # - configVersion = 0: "hoisted" linker = "hoisted" # minimum age config minimumReleaseAge = 259200 # seconds minimumReleaseAgeExcludes = ["@types/node", "typescript"] ``` -------------------------------- ### Create a new TanStack Start app Source: https://bun.com/docs/guides/ecosystem/tanstack-start Use the interactive CLI to create a new TanStack Start app. This command initiates the project setup process. ```sh bunx @tanstack/cli create my-tanstack-app ``` -------------------------------- ### Install Dependencies for All Workspaces Source: https://bun.com/docs/guides/install/workspaces Run `bun install` from the project root to install all dependencies for all defined workspaces. ```sh bun install ``` -------------------------------- ### Install Gel Client and Codegen Source: https://bun.com/docs/guides/ecosystem/gel Install the Gel JavaScript client library and its codegen CLI using Bun. ```sh bun add gel bun add -D @gel/generate touch seed.ts ``` -------------------------------- ### Install and Use Bun in GitHub Actions Workflow Source: https://bun.com/docs/guides/runtime/cicd This snippet shows a basic GitHub Actions workflow that checks out code, installs Bun using the setup-bun action, and then runs common Bun commands like install, execute, and build. ```yaml name: my-workflow jobs: my-job: name: my-job runs-on: ubuntu-latest steps: # ... - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 # [!code ++] # run any `bun` or `bunx` command - run: bun install # [!code ++] - run: bun index.ts # [!code ++] - run: bun run build # [!code ++] ``` -------------------------------- ### Install React and ReactDOM Source: https://bun.com/docs/bundler/standalone-html Install the necessary React packages using Bun. ```bash bun install react react-dom ``` -------------------------------- ### Example systemd service file for a Bun application Source: https://bun.com/docs/guides/ecosystem/systemd A template for a systemd service file. Customize User, WorkingDirectory, and ExecStart to match your application's setup. Ensure absolute paths are used for ExecStart. ```ini [Unit] # describe the app Description=My App # start the app after the network is available After=network.target [Service] # usually you'll use 'simple' # one of https://www.freedesktop.org/software/systemd/man/systemd.service.html#Type= Type=simple # which user to use when starting the app User=YOUR_USER # path to your application's root directory WorkingDirectory=/home/YOUR_USER/path/to/my-app # the command to start the app # requires absolute paths ExecStart=/home/YOUR_USER/.bun/bin/bun run index.ts # restart policy # one of {no|on-success|on-failure|on-abnormal|on-watchdog|on-abort|always} Restart=always [Install] # start the app automatically WantedBy=multi-user.target ``` -------------------------------- ### Configure Dry Run for Installation Source: https://bun.com/docs/runtime/bunfig When true, `bun install` will not actually install dependencies. Defaults to false. ```toml [install] dryRun = false ``` -------------------------------- ### Basic HTTP Server Setup with Routes Source: https://bun.com/docs/runtime/http/server Demonstrates setting up a basic HTTP server with static, dynamic, method-specific, wildcard, and redirect routes. Also shows how to serve a file. ```typescript const server = Bun.serve({ // `routes` requires Bun v1.2.3+ routes: { // Static routes "/api/status": new Response("OK"), // Dynamic routes "/users/:id": req => { return new Response(`Hello User ${req.params.id}!`); }, // Per-HTTP method handlers "/api/posts": { GET: () => new Response("List posts"), POST: async req => { const body = await req.json(); return Response.json({ created: true, ...body }); }, }, // Wildcard route for all routes that start with "/api/" and aren't otherwise matched "/api/*": Response.json({ message: "Not found" }, { status: 404 }), // Redirect from /blog/hello to /blog/hello/world "/blog/hello": Response.redirect("/blog/hello/world"), // Serve a file by lazily loading it into memory "/favicon.ico": Bun.file("./favicon.ico"), }, // (optional) fallback for unmatched routes: // Required if Bun's version < 1.2.3 fetch(req) { return new Response("Not Found", { status: 404 }); }, }); console.log(`Server running at ${server.url}`); ``` -------------------------------- ### gcloud init output example Source: https://bun.com/docs/guides/deployment/google-cloud-run Example output from the `gcloud init` command, showing the process of signing in and selecting or creating a project. ```txt Welcome! This command will take you through the configuration of gcloud. You must sign in to continue. Would you like to sign in (Y/n)? Y You are signed in as [email@example.com]. Pick cloud project to use: [1] existing-bun-app-1234 [2] Enter a project ID [3] Create a new project Please enter numeric choice or text value (must exactly match list item): 3 Enter a Project ID. my-bun-app Your current project has been set to: [my-bun-app] The Google Cloud CLI is configured and ready to use! ``` -------------------------------- ### Nested Transaction Example Source: https://bun.com/docs/runtime/sqlite Demonstrates how to use nested transactions, where an inner transaction functions as a savepoint. This example includes setup for tables and prepared statements. ```typescript // setup import { Database } from "bun:sqlite"; const db = Database.open(":memory:"); db.run("CREATE TABLE expenses (id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, dollars INTEGER);"); db.run("CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)"); const insertExpense = db.prepare("INSERT INTO expenses (note, dollars) VALUES (?, ?)"); const insert = db.prepare("INSERT INTO cats (name, age) VALUES ($name, $age)"); const insertCats = db.transaction(cats => { for (const cat of cats) insert.run(cat); }); const adopt = db.transaction(cats => { insertExpense.run("adoption fees", 20); insertCats(cats); // nested transaction }); adopt([ { $name: "Joey", $age: 2 }, { $name: "Sally", $age: 4 }, { $name: "Junior", $age: 1 }, ]); ``` -------------------------------- ### Start an HTTP Server with Bun.serve Source: https://bun.com/docs/runtime/bun-apis This snippet demonstrates how to start a basic HTTP server using `Bun.serve`. It listens for incoming requests and responds with 'Success!'. ```typescript Bun.serve({ fetch(req: Request) { return new Response("Success!"); }, }); ``` -------------------------------- ### Install Testing Libraries Source: https://bun.com/docs/guides/test/svelte-test Install the necessary packages for testing Svelte components with Bun. ```bash bun add @testing-library/svelte svelte@4 @happy-dom/global-registrator ``` -------------------------------- ### Basic Bun Build Command Source: https://bun.com/docs/bundler/esbuild This is a basic example of how to use the bun build command with an entrypoint and an output directory. ```bash bun build --outdir=out ``` -------------------------------- ### API Server Setup with Lifecycle Hooks Source: https://bun.com/docs/test/lifecycle Starts an API server before all tests and stops it after all tests. ```typescript import { beforeAll, afterAll } from "bun:test"; import { startServer, stopServer } from "./server"; let server; beforeAll(async () => { // Start test server server = await startServer({ port: 3001, env: "test", }); }); afterAll(async () => { // Stop test server await stopServer(server); }); ``` -------------------------------- ### Initialize Bun Project and Add Neon Serverless Driver Source: https://bun.com/docs/guides/ecosystem/neon-serverless-postgres Create a new Bun project directory, initialize it with `bun init`, and add the Neon serverless driver as a dependency. ```sh mkdir bun-neon-postgres cd bun-neon-postgres bun init -y bun add @neondatabase/serverless ``` -------------------------------- ### Glob Pattern '!' Negation Example Source: https://bun.com/docs/runtime/glob Demonstrates the '!' glob pattern, which negates the match result at the start of a pattern. ```typescript const glob = new Glob("!index.ts"); glob.match("index.ts"); // => false glob.match("foo.ts"); // => true ``` -------------------------------- ### Query Result (Get) Source: https://bun.com/docs/runtime/sqlite Example output format for the `.get()` method, showing the first result as an object. ```text { $message: "Hello world" } ``` -------------------------------- ### Configure Debugger Port and URL Source: https://bun.com/docs/runtime/debugger Examples of how to specify a custom port, URL, or both for the Bun debugger when starting a script. ```sh bun --inspect=4000 server.ts ``` ```sh bun --inspect=localhost:4000 server.ts ``` ```sh bun --inspect=localhost:4000/prefix server.ts ``` -------------------------------- ### Example YAML Configuration Source: https://bun.com/docs/guides/runtime/import-yaml A sample YAML file demonstrating nested configurations for database, server, and features. ```yaml database: host: localhost port: 5432 name: myapp server: port: 3000 timeout: 30 features: auth: true rateLimit: true ``` -------------------------------- ### Example React App Component Source: https://bun.com/docs/bundler/standalone-html A simple React component to be rendered within the HTML file. Ensure React is installed in your project. ```tsx import React from "react"; import { createRoot } from "react-dom/client"; function App() { return

Hello from a single HTML file!

; } createRoot(document.getElementById("root")!).render(); ``` -------------------------------- ### Start a Basic WebSocket Server Source: https://bun.com/docs/runtime/http/websockets This snippet shows how to set up a basic WebSocket server using Bun.serve(). The fetch handler upgrades incoming requests to WebSocket connections. It returns an error if the upgrade fails. ```typescript Bun.serve({ fetch(req, server) { // upgrade the request to a WebSocket if (server.upgrade(req)) { return; } return new Response("Upgrade failed", { status: 500 }); }, websocket: {}, // handlers }); ``` -------------------------------- ### Define a Custom Bun Plugin Source: https://bun.com/docs/bundler/plugins Example of defining a custom Bun plugin with a name and a setup function. This plugin can then be passed to `Bun.build`. ```typescript import type { BunPlugin } from "bun"; const myPlugin: BunPlugin = { name: "Custom loader", setup(build) { // implementation }, }; ``` -------------------------------- ### Add Nitro to your project Source: https://bun.com/docs/guides/ecosystem/tanstack-start Install the Nitro build tool to your project. This tool facilitates the deployment of your TanStack Start application to different platforms. ```sh bun add nitro ``` -------------------------------- ### Start the SvelteKit development server Source: https://bun.com/docs/guides/ecosystem/sveltekit Navigate into your project directory and start the development server using Bun. The `--bun` flag ensures Bun is used for running the dev server. ```sh cd my-app bun --bun run dev ``` ```txt $ vite dev Forced re-optimization of dependencies VITE v5.4.10 ready in 424 ms ➜ Local: http://localhost:5173/ ➜ Network: use --host to expose ➜ press h + enter to show help ``` -------------------------------- ### Complete Bun.build() Example with Compile Options Source: https://bun.com/docs/bundler/executables A full example demonstrating how to use `Bun.build()` with detailed `compile` options, including target, outfile, execArgv, and disabling dotenv/bunfig loading. ```typescript import type { BunPlugin } from "bun"; const myPlugin: BunPlugin = { name: "my-plugin", setup(build) { // Plugin implementation }, }; const result = await Bun.build({ entrypoints: ["./src/cli.ts"], compile: { target: "bun-linux-x64", outfile: "./dist/mycli", execArgv: ["--smol"], autoloadDotenv: false, autoloadBunfig: false, }, minify: true, sourcemap: "linked", bytecode: true, define: { "process.env.NODE_ENV": JSON.stringify("production"), VERSION: JSON.stringify("1.0.0"), }, plugins: [myPlugin], }); if (result.success) { console.log("Build successful:", result.outputs[0].path); } ``` -------------------------------- ### Async Lifecycle Hooks Example Source: https://bun.com/docs/test/lifecycle Demonstrates the use of asynchronous functions for beforeAll and afterAll hooks, allowing for async setup and teardown operations. ```typescript import { beforeAll, afterAll, test } from "bun:test"; beforeAll(async () => { // Async setup await new Promise(resolve => setTimeout(resolve, 100)); console.log("Async setup complete"); }); afterAll(async () => { // Async teardown await new Promise(resolve => setTimeout(resolve, 100)); console.log("Async teardown complete"); }); test("async test", async () => { // Test will wait for beforeAll to complete await expect(Promise.resolve("test")).resolves.toBe("test"); }); ``` -------------------------------- ### Simple HTTP Server Source: https://bun.com/docs/guides/http/simple Starts an HTTP server on port 3000 that responds to all requests with 'Welcome to Bun!'. Use this for basic server setup. ```typescript const server = Bun.serve({ port: 3000, fetch(request) { return new Response("Welcome to Bun!"); }, }); console.log(`Listening on ${server.url}`); ``` -------------------------------- ### Install NAPI CLI and create new project Source: https://bun.com/docs/bundler/plugins Installs the NAPI CLI globally and initiates a new NAPI project. This is the first step in creating a native plugin. ```bash bun add -g @napi-rs/cli napi new ``` -------------------------------- ### Environment variables output example Source: https://bun.com/docs/guides/deployment/google-cloud-run Example output after setting project environment variables, displaying the project ID and number. ```txt my-bun-app-... [PROJECT_NUMBER] ``` -------------------------------- ### Capture Stack Trace from a Specific Function with Error.captureStackTrace Source: https://bun.com/docs/runtime/debugger Utilize `Error.captureStackTrace` to set the starting point of a stack trace, useful for asynchronous code or callbacks. This example captures the stack trace starting from the `fn` function, ignoring internal calls like `myInner`. ```typescript const fn = () => { function myInner() { throw err; } try { myInner(); } catch (err) { console.log(err.stack); console.log(""); console.log("-- captureStackTrace --"); console.log(""); Error.captureStackTrace(err, fn); console.log(err.stack); } }; fn(); ``` -------------------------------- ### Initialize StricJS Project and Add Dependencies Source: https://bun.com/docs/guides/ecosystem/stric Use `bun init` to create a new project, then add the StricJS router and utility packages. ```bash mkdir myapp cd myapp bun init bun add @stricjs/router @stricjs/utils ``` -------------------------------- ### Initialize Qwik App with Bun Source: https://bun.com/docs/guides/ecosystem/qwik Use `bun create qwik` to scaffold a new Qwik project. Bun automatically detects and uses itself for dependency installation. ```sh bun create qwik ``` -------------------------------- ### Initialize Project with Bun Source: https://bun.com/docs/guides/ecosystem/discordjs Create a new project folder and initialize it using Bun's package manager. This sets up the basic project structure. ```sh mkdir my-bot cd my-bot bun init ``` -------------------------------- ### Import aliased package in TypeScript Source: https://bun.com/docs/guides/install/npm-alias After installing a package with an alias, import it using the custom name in your TypeScript code. This example shows importing 'zod' as 'my-custom-name'. ```ts import { z } from "my-custom-name"; z.string(); ``` -------------------------------- ### Astro Project Initialization Output Source: https://bun.com/docs/guides/ecosystem/astro This is the output from the `bun create astro` command, showing the project setup process and next steps. ```txt ╭─────╮ Houston: │ ◠ ◡ ◠ We're glad to have you on board. ╰─────╯ astro v3.1.4 Launch sequence initiated. dir Where should we create your new project? ./fumbling-field tmpl How would you like to start your new project? Use blog template ✔ Template copied deps Install dependencies? Yes ✔ Dependencies installed ts Do you plan to write TypeScript? Yes use How strict should TypeScript be? Strict ✔ TypeScript customized git Initialize a new git repository? Yes ✔ Git initialized next Liftoff confirmed. Explore your project! Enter your project directory using cd ./fumbling-field Run `bun run dev` to start the dev server. CTRL+C to stop. Add frameworks like react or tailwind using astro add. Stuck? Join us at https://astro.build/chat ╭─────╮ Houston: │ ◠ ◡ ◠ Good luck out there, astronaut! 🚀 ╰─────╯ ``` -------------------------------- ### Initialize TanStack Start Server Handler Source: https://bun.com/docs/guides/ecosystem/tanstack-start Imports the default export from the server entry point to get the application handler. Exits if the handler fails to load. ```javascript let handler: { fetch: (request: Request) => Response | Promise } try { const serverModule = (await import(SERVER_ENTRY_POINT)) as { default: { fetch: (request: Request) => Response | Promise } } handler = serverModule.default log.success('TanStack Start application handler initialized') } catch (error) { log.error(`Failed to load server handler: ${String(error)}`) process.exit(1) } ``` -------------------------------- ### Fetch Info from Docker Socket Source: https://bun.com/docs/guides/http/fetch-unix Send a GET request to retrieve information from the Docker daemon's socket. This example demonstrates fetching JSON data. ```typescript const unix = "/var/run/docker.sock"; const response = await fetch("http://localhost/info", { unix }); const body = await response.json(); console.log(body); // { ... } ``` -------------------------------- ### Create a SolidStart App with TypeScript Source: https://bun.com/docs/guides/ecosystem/solidstart Use `bun create` with the `--solidstart` and `--ts` flags to initialize a new SolidStart project. Select the 'basic' template when prompted. ```sh bun create solid my-app --solidstart --ts ``` -------------------------------- ### Specify Bun Version in GitHub Actions Workflow Source: https://bun.com/docs/guides/runtime/cicd This example demonstrates how to specify a particular version of Bun to be installed in your GitHub Actions workflow using the `bun-version` input for the setup-bun action. ```yaml name: my-workflow jobs: my-job: name: my-job runs-on: ubuntu-latest steps: # ... - uses: oven-sh/setup-bun@v2 with: # [!code ++] bun-version: 1.3.3 # or "latest", "canary", # [!code ++] ``` -------------------------------- ### Bun Install CLI: General Configuration Options Source: https://bun.com/docs/pm/cli/install Specify configuration file path or set the current working directory for the installation. ```sh bun install --config bunfig.toml ``` ```sh bun install --cwd /path/to/directory ``` -------------------------------- ### CI/CD Bytecode Generation (GitHub Actions) Source: https://bun.com/docs/bundler/bytecode Example of generating bytecode during a CI/CD pipeline using a GitHub Actions workflow. This snippet shows the 'run' command to install dependencies and build the project with bytecode. ```yaml # GitHub Actions - name: Build with bytecode run: | bun install bun build --bytecode --minify \ --outdir=./dist \ --target=bun \ ./src/index.ts ``` -------------------------------- ### Gel Project Initialization Output Source: https://bun.com/docs/guides/ecosystem/gel Example output from `gel project init`, showing project details and initialization status. ```txt No `gel.toml` found in `/Users/colinmcd94/Documents/bun/fun/examples/my-gel-app` or above Do you want to initialize a new project? [Y/n] > Y Specify the name of Gel instance to use with this project [default: my_gel_app]: > my_gel_app Checking Gel versions... Specify the version of Gel to use with this project [default: x.y]: > x.y ┌─────────────────────┬──────────────────────────────────────────────────────────────────┐ │ Project directory │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app │ │ Project config │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/gel.toml│ │ Schema dir (empty) │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema│ │ Installation method │ portable package │ │ Version │ x.y+6d5921b │ │ Instance name │ my_gel_app │ └─────────────────────┴──────────────────────────────────────────────────────────────────┘ Version x.y+6d5921b is already downloaded Initializing Gel instance... Applying migrations... Everything is up to date. Revision initial Project initialized. To connect to my_gel_app, run `gel` ``` -------------------------------- ### Configure Module Resolution with onResolve Source: https://bun.com/docs/bundler/plugins Customizes how Bun resolves module imports. This example redirects imports starting with `images/` to a different path. The `filter` and `namespace` arguments allow for targeted resolution logic. ```typescript import { plugin } from "bun"; plugin({ name: "onResolve example", setup(build) { build.onResolve({ filter: /.*/, namespace: "file" }, args => { if (args.path.startsWith("images/")) { return { path: args.path.replace("images/", "./public/images/"), }; } }); }, }); ``` -------------------------------- ### Building with CLI Source: https://bun.com/docs/bundler/index Initiate a build process directly from the command line, specifying the entrypoint. ```bash bun build ./index.ts ``` -------------------------------- ### Run Prisma migrations with bunx Source: https://bun.com/docs/pm/bunx Example of using bunx to execute a common CLI tool for database migrations. ```bash bunx prisma migrate ``` -------------------------------- ### Serve HTML files and API routes Source: https://bun.com/docs/bundler/fullstack Import HTML files and pass them to the `routes` option in `Bun.serve()`. This example demonstrates serving static HTML files and defining API endpoints for GET and POST requests. ```typescript import { serve } from "bun"; import dashboard from "./dashboard.html"; import homepage from "./index.html"; const server = serve({ routes: { // ** HTML imports ** // Bundle & route index.html to "/". This uses HTMLRewriter to scan // the HTML for `