Install the package via bun add --dev bun-workspaces to use the API.
Note that you need to run bun install in your project forbun-workspaces to find your project's workspaces, and you likely must run this again after you've updated your workspaces.
See the Glossary for more fundamental concepts.
Required Bun version: ^1.2.0
createFileSystemProject(options: CreateFileSystemProjectOptions): FileSystemProject
Create a FileSystemProject, the core of bun-workspaces's functionality, based on a given root directory.
This finds Workspaces by reading the project's bun.lock file, which means bun install must be run to have up-to-date
workspace information.
It will also detect and utilize any root configuration and workspace configurations found.
import { createFileSystemProject } from "bun-workspaces";
// Root directory defaults to process.cwd()
const defaultProject = createFileSystemProject();
const pathProject = createFileSystemProject({
rootDirectory: "./path/to/project/root" // relative from process.cwd()
});
// Include the root workspace as a normal workspace (overrides config/env settings)
const projectWithRoot = createFileSystemProject({
includeRootWorkspace: true,
});
An object representing a workspace in a Project.
Set workspace aliases in the workspace configuration to make it easier to reference workspaces.
See more on the root workspace.
{
// The name of the workspace from its package.json
name: "my-workspace",
// Whether the workspace is the root workspace
isRoot: false,
// The relative path to the workspace from the project root
path: "my/workspace/path",
// The glob pattern from the root package.json "workspaces" field
// that this workspace was matched from
matchPattern: "my/workspace/pattern/*",
// The scripts available in the workspace's package.json
scripts: ["my-script"],
// Aliases defined in workspace configuration (see the Configuration section)
aliases: ["my-alias"],
// Names of other workspaces that this workspace depends on
dependencies: ["my-dependency"],
// Names of other workspaces that depend on this workspace
dependents: ["my-dependent"],
}
The core of bun-workspaces's functionality.
It contains a list of Workspaces and provides
several useful methods for working with them. A Project is typically initialized at a git repository's root directory.
The Project root should contain the package.json file in which "workspaces" are defined.
Usually created via createFileSystemProject.
type: string
The name of the project. This is typically the name found in the root package.json unless otherwise provided.
type: string
The given root directory of the project.
type: Workspace[]
The list of all Workspaces in the project.
type: Workspace
The root workspace of the project.
findWorkspaceByName(workspaceName: string): Workspace | null
Find a Workspace by its package.json name.
// Find a workspace by its package.json name (or returns null)
const workspace = project.findWorkspaceByName("my-workspace");
findWorkspaceByAlias(alias: string): Workspace | null
Find a Workspace by its alias, if set in its workspace configuration.
// Find a workspace by its alias (or returns null)
const workspace = project.findWorkspaceByAlias("my-alias");
findWorkspaceByNameOrAlias(nameOrAlias: string): Workspace | null
Find a Workspace by its package.json name or alias, if set in its workspace configuration.
Since aliases are validated to be unique to each workspace and not clash with other workspaces' package.json names, this method can still unambiguously find a workspace.
// Find a workspace by its package.json name or alias (or returns null)
const workspace = project.findWorkspaceByNameOrAlias("my-workspace");
findWorkspacesByPattern(workspacePattern: string): Workspace[]
Find a list of Workspaces by their name, using a wildcard pattern.
See more on the syntax of workspace patterns.
// An array of workspaces whose names match the wildcard pattern
const workspaces = project.findWorkspacesByPattern(
"my-name-pattern-*",
"alias:my-alias-*",
"path:packages/**/*",
);
listWorkspacesWithScript(scriptName: string): Workspace[]
Get an array of all Workspaces that have a given script in their package.json "scripts" field.
// An array of workspaces that have "my-script"
// in their package.json "scripts" field
const workspaces = project.listWorkspacesWithScript("my-script"));
mapScriptsToWorkspaces(): Record<string, WorkspaceScriptMetadata>
Get a mapping of all project script names to the Workspaces that have them in their package.json "scripts" field.
// An object mapping all script names to the workspaces
// that have them in their package.json "scripts" field
const scriptMap = project.mapScriptsToWorkspaces();
// An array of Workspaces
const { workspaces } = scriptMap["my-script"];
createScriptCommand(options: CreateProjectScriptCommandOptions): CreateProjectScriptCommandResult
Create metadata that can be used to run a Workspace's script.
The "method" option changes what kind of bun command is implemented to run the script.
"cd" (the default) is generally recommended over "filter" in order to get full stdout/stderr output from the script.
// Does not run a script, but provides
// metadata that can be used to do so.
const {
commandDetails: { command, workingDirectory },
} = project.createScriptCommand({
scriptName: "my-script",
workspaceNameOrAlias: "my-workspace",
method: "cd", // optional, defaults to "cd" (other option "filter")
args: "--my-appended-args", // optional, append args to the command
});
// A means by which you may actually run the script
const subprocess = Bun.spawn(["sh", "-c", command], {
cwd: workingDirectory,
});
Inherits from Project. Used to represent a project in the file system. Created via createFileSystemProject.
Includes methods for running scripts in the workspaces of the project.
runWorkspaceScript(options: RunWorkspaceScriptOptions): RunWorkspaceScriptResult
Run a script in a given workspace.
const { output, exit } = project.runWorkspaceScript({
workspaceNameOrAlias: "my-workspace",
script: "my-script",
args: "--my --appended --args", // optional, arguments to add to the command
});
// Get a stream of the script subprocess's output
for await (const { outputChunk } of output) {
// outputChunk.raw // The raw output content (Uint8Array)
// outputChunk.decode() // The output chunk's content (string)
// outputChunk.decode({ stripAnsi: true }) // Text with ANSI codes sanitized (string)
// outputChunk.streamName // The output stream, "stdout" or "stderr"
}
// Get data about the script execution after it exits
const exitResult = await exit;
// exitResult.exitCode // The exit code (number)
// exitResult.signal // The exit signal (string), or null
// exitResult.success // true if exit code was 0
// exitResult.startTimeISO // Start time (string)
// exitResult.endTimeISO // End time (string)
// exitResult.durationMs // Duration in milliseconds (number)
// exitResult.metadata.workspace // The target workspace (Workspace)
runScriptAcrossWorkspaces(options: RunScriptAcrossWorkspacesOptions): RunScriptAcrossWorkspacesResult
,
Run a script in all workspaces that have it in their package.json "scripts" field.
const { output, summary } = project.runScriptAcrossWorkspaces({
// Optional. This will run in all matching workspaces that have my-script
// Accepts same values as the CLI run-script command's workspace patterns
// When not provided, all workspaces that have the script will be used.
workspacePatterns: ["my-workspace", "my-name-pattern-*"],
// Required. The package.json "scripts" field name to run
script: "my-script",
// Optional. Arguments to add to the command
args: "--my --appended --args",
// Optional. Whether to run the scripts in parallel
parallel: true,
});
// Get a stream of script output
for await (const { outputChunk, scriptMetadata } of output) {
// outputChunk.decode() // the output chunk's content (string)
// outputChunk.decode({ stripAnsi: true }) // text with ANSI codes sanitized (string)
// outputChunk.streamName // "stdout" or "stderr"
// The metadata can distinguish which workspace script
// the current output chunk came from
// scriptMetadata.workspace // Workspace object
}
// Get final summary data and script exit details after all scripts have completed
const summaryResult = await summary;
// summaryResult.totalCount // Total number of scripts
// summaryResult.allSuccess // true if all scripts succeeded
// summaryResult.successCount // Number of scripts that succeeded
// summaryResult.failureCount // Number of scripts that failed
// summaryResult.startTimeISO // Start time (string)
// summaryResult.endTimeISO // End time (string)
// summaryResult.durationMs // Total duration in milliseconds (number)
// The exit details of each workspace script
for (const exitResult of summaryResult.scriptResults) {
// exitResult.exitCode // The exit code (number)
// exitResult.signal // The exit signal (string), or null
// exitResult.success // true if exit code was 0
// exitResult.startTimeISO // Start time (ISO string)
// exitResult.endTimeISO // End time (ISO string)
// exitResult.durationMs // Duration in milliseconds (number)
// exitResult.metadata.workspace // The target workspace (Workspace)
}
See more on the syntax of workspace patterns for selecting workspaces to run.
See more on running inline scripts.
See more on running parallel scripts.
See more on script runtime metadata, such as environment variables available in scripts and interpolating values in inline scripts and args such as <workspaceName>.
createMemoryProject(options: CreateMemoryProjectOptions): MemoryProject
Create a Project from a given array of Workspaces.
Usually used only for testing purposes to do without the need for a real project in the file system.
Since it doesn't read anything from the file system, it isn't affected by root configuration or workspace configurations.
A MemoryProject currently does not support running scripts directly, though a means of mocking script execution may be added later, considering demand.
import { createMemoryProject } from "bun-workspaces";
const testProject = createMemoryProject({
rootDirectory: "test-project-directory", // optional
name: "test-project", // optional
workspaces: [
{
name: "my-test-workspace",
path: "my/test/workspace/path",
matchPattern: "my/test/workspace/pattern/*",
scripts: ["my-test-script"],
aliases: ["test-alias"],
dependencies: [],
dependents: []
}
]
});
setLogLevel(level: LogLevelSetting)
Set the global logging level. Defaults to "info" or "error" when NODE_ENV is "test".
import { setLogLevel } from "bun-workspaces";
setLogLevel("debug");
setLogLevel("info" // default
setLogLevel("warn");
setLogLevel("error" // default when NODE_ENV is "test"
setLogLevel("silent");