Running scripts in Typescript doesn’t need to be hard.
Bun is a powerful new tool and runtime for Typescript and Javascript, and the CLI lets you run Typescript files directly.
So running a script is as easy as:
bun run my-script.ts
Check this out:
/** my-script.ts **/
console.log("There's a bun in the oven!");
// CLI: bun run my-script.ts
// output: There's a bun in the oven!
You still need script flags, though. After all, what if we don’t know where the bun is until we run the script? How do we get information into the script at runtime?
bun run my-script.ts --location oven
...
/** my-script.ts **/
const location = ???;
console.log(`There's a bun in the ${location}!`);
Luckily, Vercel has built a great package for parsing arguments, which is extremely easy to use.
bun run my-script.ts --location oven
...
/** my-script.ts **/
import arg from "arg";
const argument = arg({
'--location': String,
});
const location = argument["--location"];
console.log(`There's a bun in the ${location}!`);
From the Top
Create a new directory and instantiate a typescript project
mkdir script-folder cd script-folder tsc --init
Install Bun (if not installed already)
curl -fsSL https://bun.sh/install | bash
Install arg
npm i arg
Create your file and copy the below code into the file
touch my-script.ts
/** my-script.ts **/ import arg from "arg"; const argument = arg({ '--location': String, }); const location = argument["--location"]; console.log(`There's a bun in the ${location}!`);
Run the script
bun run my-script.ts --location oven
Wrapping Up
I wrote this after running into absolutely zero Google results for how to easily run a script with flags in typescript, while putting together a project for my bootcamp students. You can thank them for this!
If you’re feeling particularly lazy, the code is available here to clone or fork (contributions always welcome).