Package Scripts
Automate repeat work with scripts in box.json, run them by name, and hook into CommandBox lifecycle events.
On this page
In this lesson you will add scripts to your box.json, run them with run-script, and attach commands to lifecycle events like installs and server starts.
Ad-hoc scripts
A scripts struct in box.json holds named commands. Each value is any command you could type in the CommandBox shell.
{
"name": "My Package",
"slug": "my-package",
"version": "1.0.0",
"scripts": {
"generateAPIDocs": "docbox generate",
"build": "testbox run && run-script generateAPIDocs"
}
}
Run them by name:
box run-script generateAPIDocs
box run-script build
A command that errors stops the chain, just like && in a shell.
Several commands as a list
For readability, a script can be an array. It behaves the same as joining the commands with &&.
{
"scripts": {
"build": [
"testbox run",
"run-script generateAPIDocs",
"bump --patch"
]
}
}
Passing parameters
Extra arguments to run-script become environment variables inside the script.
box run-script greet Luis
{
"scripts": {
"greet": "echo Hello ${1}"
}
}
Named form: every argument must be named, including the script name.
box run-script scriptName=greet name1=Luis
pre and post scripts
Before any script runs, CommandBox looks for a script with the same name prefixed with pre. After it, it looks for one prefixed with post. So build runs as preBuild, build, postBuild.
Lifecycle hooks
Scripts named after a CommandBox interception point run automatically when that event fires. The ones you will use most:
| Script name | Fires |
|---|---|
preInstall | before a package is installed |
postInstall | after an install completes |
preServerStart | before a server starts |
onServerInstall | when a server starts and its engine is being installed |
{
"scripts": {
"postInstall": "echo Install finished",
"onServerStart": "touch ${interceptData.serverInfo.serverHomeDirectory}/hi.txt"
}
}
Hooks can read event data as environment variables prefixed with interceptData.. Use env show inside a script to dump what is available.
Server related scripts can also live in a project's server.json.
Recap
- Put named commands under
scriptsinbox.jsonand run them withbox run-script <name>. - Scripts can be arrays, take parameters as
${1}` or `${name}, and getpreandpostvariants for free. - Name a script after an interception point such as
postInstallorpreServerStartand it runs on that event.