Quickly Create Scripts with tsx
Sometimes you'll want to run quick scripts when working on a frontend or backend app.
With the tsx
command, you can write these script in TypeScript.
As an example, inside of package.json
we tsx
as a devDependency
as well as a script called do-something
:
// inside package.
Transcript
00:00 Often when you're working in a front-end app or a back-end app too, you're going to want to run just some quick scripts every now and again. These scripts could be absolutely anything, and sometimes you don't want to write them in Bash. Sometimes you want to write them in, let's say, TypeScript. So we have a script here called DoSomething,
00:17 and this script, what it does, just says console.log, the script is working. Then it takes in any arguments that you pass it from process.argv, and then it just console.logs those args. So I have set this up with something called TSX, and TSX, as you can see, is a dev dependency here.
00:34 What TSX does is it runs basically ES build on the TypeScript files, and that bundles them into JavaScript. Then it will just run those JavaScript files. And it does this extremely fast, and it doesn't do any type checking, crucially, too.
00:51 So TSX is a really great way to just quickly run a TypeScript file if you just need a script to do something. So inside this directory, I can say pnpm run do-something, and I can pass it some arguments if I want to. So I'll say A, B, and C, like this.
01:09 And now, as you can see, it ran TSX on scripts do-something.ts, passing it A, B, and C, and then it said the script is working, and I've got my arguments back here, so A, B, and C. This is great for if you just want to, I don't know, run a database migration, or just run some local stuff,
01:29 and you have access to all of the things that Node can do inside here, too. So we have it just inside scripts.ts, do-something.ts. It's a really, really nice system for just quickly running a script locally using TypeScript.