Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Package Manager and Scripts

Scripts and bunx

Define package.json scripts and run them with bun run, use pre and post hooks, pass arguments, run local binaries and one-off tools with bunx, and force the Bun runtime with --bun.

Typing long commands from memory does not scale. The scripts section of package.json gives each command a short name, so a team can agree on bun run dev, bun run check and bun run build no matter what tools sit behind them. Bun runs these scripts quickly and understands the Node.js conventions around them. Its sibling bunx runs a package's executable without installing it globally. This lesson shows both.

Defining and running scripts

JSON
{
  "scripts": {
    "dev": "bun --watch src/index.ts",
    "start": "bun src/index.ts",
    "check": "tsc --noEmit",
    "format": "prettier --write .",
    "build": "bun build src/index.ts --outdir dist --target bun",
    "clean": "rm -rf dist"
  }
}
Terminal
bun run dev
bun run check

bun run with no name lists every script in the file, which is a handy reminder. Two shortcuts apply: bun dev works when the name does not collide with a Bun subcommand, and bun run also executes files (bun run src/index.ts), so a script name and a file path are told apart by whether a script of that name exists.

Collisions are the usual trap: bun test always means Bun's test runner. To run a script called test, use bun run test. The same applies to build, install, add, init and other subcommand names.

How a script runs

When Bun runs a script it:

  1. adds node_modules/.bin (and parent folders' .bin) to PATH, so installed tools like tsc and prettier work by bare name;
  2. runs the command string in a shell;
  3. forwards the exit code, so a failing step fails the whole command (important in CI);
  4. makes bun itself behave as node for tools that call it, if Node is not installed.

Because node_modules/.bin is on the path, "check": "tsc --noEmit" needs no npx or bunx prefix once TypeScript is a dependency.

Shell syntax such as && (run next if previous succeeded), ||, ;, pipes, redirects and NAME=value prefixes work on every operating system, including Windows, because Bun provides a cross-platform shell for scripts. Keep scripts simple, and for anything complex write a scripts/something.ts file and call it:

JSON
{ "scripts": { "release": "bun run scripts/release.ts" } }

A TypeScript script gets types, loops, error handling and Bun.$ for shell commands, and it behaves the same everywhere.

Passing arguments

Everything after the script name is appended to the command:

Terminal
bun run dev --port 4000
bun run format -- --check

With "dev": "bun --watch src/index.ts", the first line runs bun --watch src/index.ts --port 4000, so your program sees --port 4000 in Bun.argv. The standalone -- separator is also accepted and passes the rest through unchanged. If you chain commands with &&, arguments are added to the end of the whole string, so pass them to the intended command another way (for example through a TypeScript script).

Pre and post hooks

Name a script preX or postX and Bun runs it automatically before or after X:

JSON
{
  "scripts": {
    "prebuild": "bun run clean",
    "build": "bun build src/index.ts --outdir dist",
    "postbuild": "echo build finished",
    "clean": "rm -rf dist"
  }
}

bun run build runs prebuild, then build, then postbuild. If any step exits non-zero, the chain stops. The hooks do not nest: running bun run clean directly does not trigger preclean. Because this behaviour is implicit, teams sometimes avoid hooks and write the steps explicitly ("build": "bun run clean && bun build ..."). Either is fine; choose one style.

Lifecycle names such as postinstall, prepare and prepublishOnly are run by the package manager at the appropriate moments for your own project, as described in the lockfile lesson.

A stand-in script runner

The pre/post rule is easy to model. This runnable stand-in implements the same algorithm over a scripts object, so you can try different names:

Node.js Stand-in: script lookup with pre and post hooks (Node 24)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Try replacing 'build' with 'clean' and notice that preclean is not looked up in the log.

Running scripts in several packages

In a workspace repository (next lesson) you can target packages with a filter:

Terminal
bun run --filter "*" build            # run build in every workspace package
bun run --filter "./packages/*" test  # only packages under packages/
bun run --filter "@acme/api" dev

Bun runs the script in dependency order where it can and prefixes each line of output with the package name. See Workspaces and Catalogs.

--bun: choosing the runtime for tools

Many CLI tools (Vite, Next.js, ESLint, Prettier) start with a line #!/usr/bin/env node. When bun run vite executes such a tool, Bun by default honours the shebang and launches it with Node, if Node is installed. To run the tool under Bun's runtime instead, add --bun:

Terminal
bun run --bun vite
bun --bun run dev

Put the flag in the script when you want Bun everywhere:

JSON
{ "scripts": { "dev": "bun --bun vite" } }

You can make this the default for the project with [run] bun = true in bunfig.toml. If a tool misbehaves under Bun's runtime, remove the flag and let Node handle it, which is a reasonable first compatibility check.

bunx

bunx runs a package's executable, downloading it to the cache if necessary. It replaces npx.

Terminal
bunx prettier --check .            # uses local node_modules/.bin if present
bunx cowsay "Hello"                # downloads cowsay once, runs it
bunx create-vite@latest my-app     # specific tag or version
bunx --bun vite                    # run under the Bun runtime
bunx -p @scope/pkg tool-name       # install this package, run an executable with another name

Rules of thumb:

  • If a local node_modules/.bin/<name> exists, bunx uses it, so it picks up the version your project pinned.
  • Otherwise bunx fetches the newest matching version, caches it, and runs it. A cached tool starts almost instantly the next time.
  • The shebang matters here too: add --bun to run on Bun's runtime.
  • bunx is for tools you run occasionally. For tools your project needs regularly, install them as dev dependencies and call them from scripts so versions stay pinned.

Running a package script from another folder

Terminal
bun run --cwd packages/api dev

--cwd changes the directory first, which is handy in CI steps and monorepos.

Practical script set for a Bun project

JSON
{
  "scripts": {
    "dev": "bun --hot src/index.ts",
    "start": "bun src/index.ts",
    "test": "bun test",
    "check": "tsc --noEmit",
    "lint": "eslint .",
    "format": "prettier --write .",
    "build": "bun build src/index.ts --outdir dist --target bun --minify",
    "ci": "bun run check && bun run lint && bun test"
  }
}

Note "test": "bun test": this script lets people type bun run test, and tools that call npm test-style conventions keep working. The ci script strings the checks together so a failing one stops the rest.

Common mistakes

  • Using && for a long pipeline and expecting arguments to land in the middle. Arguments go to the last command only.
  • Relying on a global tool. The project fails on another machine; install it as a dev dependency.
  • Typing bun test when you meant the script. Use bun run test.
  • Forgetting --bun when a framework's dev server should use Bun APIs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command runs a package.json script named "build" and not the built-in bundler?

    Built-in subcommand names win. bun run build always runs the script.
  2. 2. In what order do the hooks run for "bun run build" when prebuild and postbuild exist?

    Bun runs prebuild first, then build, then postbuild, and stops on the first failure.
  3. 3. What does bunx do if node_modules/.bin already contains the tool?

    bunx prefers the project's local executable, keeping your pinned version.
  4. 4. What does the --bun flag change?

    Without it, Bun honours the node shebang and launches such tools with Node when available.

Summary

  • Scripts live in package.json and run with bun run <name>; node_modules/.bin is on the path.
  • Built-in subcommand names (test, build) take priority; use bun run test for the script.
  • Arguments after the script name are appended to the command string; preX/postX hooks run automatically.
  • Complex logic belongs in a TypeScript script run by bun run scripts/x.ts.
  • bunx runs package executables (local first, otherwise cached); --bun runs them on the Bun runtime.

Next: Workspaces and Catalogs