Skip to content

Bun Running Scripts

This chapter provides detailed instructions on Bun's script execution capabilities, including running files, package.json scripts, watch mode, and other features.

Running JavaScript/TypeScript Files

Basic Execution

bash
# Run JavaScript
bun index.js

# Run TypeScript (no compilation needed)
bun index.ts

# Run JSX/TSX
bun app.jsx
bun app.tsx

Using run Command

bash
# Explicitly use run
bun run index.ts

# Equivalent to
bun index.ts

Supported File Types

Bun natively supports multiple file types:

ExtensionDescription
.jsJavaScript
.tsTypeScript
.jsxJavaScript + JSX
.tsxTypeScript + JSX
.mjsES Module JavaScript
.mtsES Module TypeScript
.cjsCommonJS JavaScript
.ctsCommonJS TypeScript

Example

typescript
// greeting.tsx
interface Props {
  name: string;
}

function Greeting({ name }: Props) {
  return <div>Hello, {name}!</div>;
}

console.log(Greeting({ name: "Bun" }));
bash
bun greeting.tsx

package.json Scripts

Defining Scripts

json
{
  "scripts": {
    "start": "bun src/index.ts",
    "dev": "bun --watch src/index.ts",
    "build": "bun build src/index.ts --outdir dist",
    "test": "bun test",
    "lint": "eslint src/**/*.ts",
    "format": "prettier --write src/**/*.ts",
    "typecheck": "tsc --noEmit",
    "clean": "rm -rf dist node_modules"
  }
}

Running Scripts

bash
# Use run command
bun run start
bun run dev
bun run build

# start script can omit run
bun start

# Other scripts can also omit run
bun dev
bun test

Passing Arguments

bash
# Pass arguments to scripts
bun run build -- --minify

# Script definition
# "build": "bun build src/index.ts --outdir dist"
# Actual execution: bun build src/index.ts --outdir dist --minify

Watch Mode

Auto Reload

Use --watch to monitor file changes and automatically rerun:

bash
bun --watch index.ts

When index.ts or its imported files change, Bun will automatically rerun.

Watching Specific Files

bash
# Watch additional files
bun --watch index.ts --watch-file ./config.json

Hot Reload Mode

For HTTP servers, use --hot for hot reloading:

bash
bun --hot server.ts
typescript
// server.ts
const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello!");
  },
});

// Supports hot reloading
export default server;

Hot reload features:

  • Keep connections open
  • State can be preserved
  • Faster than --watch

Running Options

Common Options

bash
# Specify entry point
bun run --entry ./src/main.ts

# Set environment variables
bun run --env-file .env.production index.ts

# Silent mode (less output)
bun run --silent index.ts

# Verbose mode (more output)
bun run --verbose index.ts

Debugging Options

bash
# Enable debugger
bun --inspect index.ts

# Wait for debugger connection
bun --inspect-wait index.ts

# Specify debug port
bun --inspect=127.0.0.1:9229 index.ts

Memory and Performance

bash
# Set heap memory size
bun --smol index.ts  # Use less memory

# Preload script
bun --preload ./setup.ts index.ts

Executing Remote Scripts

Running URLs

bash
# Run remote scripts
bun run https://example.com/script.ts

Running Gists

bash
# Run GitHub Gist
bun run https://gist.github.com/user/gist-id/raw/script.ts

Executing System Commands

Shell Scripts

Bun can run shell commands defined in package.json:

json
{
  "scripts": {
    "clean": "rm -rf dist",
    "copy": "cp -r public dist/public",
    "setup": "mkdir -p dist && cp config.json dist/"
  }
}

Using Bun Shell

typescript
// shell-script.ts
import { $ } from "bun";

// Run shell command
await $`echo "Hello from Bun Shell"`;

// Capture output
const result = await $`ls -la`.text();
console.log(result);

// Pass variables
const name = "Bun";
await $`echo "Hello ${name}"`;

// Pipe operations
await $`cat file.txt | grep "pattern" | wc -l`;

Running npm Packages

Using bunx

Similar to npx, you can run npm packages:

bash
# Run installed package
bunx tsc --version

# Run and download package
bunx create-react-app my-app

# Specify version
bunx typescript@5.0 --version

Comparison with npx

bash
# Bun way (faster)
bunx vite

# npm way
npx vite

Multi-environment Configuration

Environment Variable Files

bash
# Load different environment configurations
bun --env-file .env.development index.ts
bun --env-file .env.production index.ts

Distinguishing Environments in Scripts

json
{
  "scripts": {
    "start": "bun --env-file .env.production src/index.ts",
    "dev": "bun --env-file .env.development --watch src/index.ts",
    "staging": "bun --env-file .env.staging src/index.ts"
  }
}

Lifecycle Scripts

pre and post Hooks

json
{
  "scripts": {
    "prebuild": "echo 'Starting build...'",
    "build": "bun build src/index.ts --outdir dist",
    "postbuild": "echo 'Build complete!'",
    
    "pretest": "bun run lint",
    "test": "bun test",
    "posttest": "echo 'Tests complete!'"
  }
}

Running bun run build will execute in order:

  1. prebuild
  2. build
  3. postbuild

Running Scripts in Parallel

Using bun-shell

typescript
// parallel.ts
import { $ } from "bun";

// Run multiple commands in parallel
await Promise.all([
  $`bun run build:client`,
  $`bun run build:server`,
  $`bun run build:styles`,
]);

console.log("All builds complete!");

Using concurrently

bash
bun add -d concurrently
json
{
  "scripts": {
    "dev": "concurrently \"bun run dev:server\" \"bun run dev:client\"",
    "dev:server": "bun --watch src/server/index.ts",
    "dev:client": "bun --watch src/client/index.ts"
  }
}

Script Debugging

VS Code Configuration

Create .vscode/launch.json:

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "bun",
      "request": "launch",
      "name": "Debug Bun",
      "program": "${workspaceFolder}/src/index.ts",
      "cwd": "${workspaceFolder}",
      "stopOnEntry": false,
      "watchMode": false
    },
    {
      "type": "bun",
      "request": "launch",
      "name": "Debug Bun (Watch)",
      "program": "${workspaceFolder}/src/index.ts",
      "cwd": "${workspaceFolder}",
      "watchMode": true
    }
  ]
}

Common Issues

Script Execution Fails

bash
# View detailed errors
bun run --verbose script-name

# Check script syntax
bun run --dry-run script-name

Permission Issues

bash
# Linux/macOS
chmod +x ./scripts/build.sh
bun run build

Path Issues

json
{
  "scripts": {
    "start": "bun ./src/index.ts",
    "build": "bun build ./src/index.ts --outdir ./dist"
  }
}

Use ./ to explicitly specify relative paths.

Summary

This chapter introduced:

  • ✅ Running various types of script files
  • ✅ Configuring and running package.json scripts
  • ✅ Using watch and hot reload modes
  • ✅ Debugging and performance options
  • ✅ Using Bun Shell and bunx
  • ✅ Multi-environment configuration and lifecycle hooks

Next Steps

Continue reading Package Manager to learn about Bun's high-speed package management features.

Content is for learning and research only.