Executable scripts
A hashbang (the first line starting with #!) tells the operating system which command should run a file. With a tsx hashbang, you can execute a TypeScript file as ./file.ts instead of typing a separate tsx command.
This page assumes a Unix-like environment, such as macOS or Linux, with /usr/bin/env supporting -S to split hashbang arguments. Native Windows shells do not use this execution mechanism. To run a script without a hashbang or executable permissions, use npx tsx ./file.ts from a project with tsx installed.
Project scripts
Use a project-local installation when the script belongs to a project. This lets the project declare its tsx version rather than relying on a global installation.
First, install tsx in the project. Save one of these alternatives as file.ts, choosing the package manager your project uses:
file.ts
#!/usr/bin/env -S npx tsx
console.log('argv:', process.argv.slice(2))#!/usr/bin/env -S pnpm exec tsx
console.log('argv:', process.argv.slice(2))#!/usr/bin/env -S yarn tsx
console.log('argv:', process.argv.slice(2))The selected package manager must be on your PATH. Run the script from the project directory so the package manager can find the local tsx installation. Install dependencies first: npx can offer to download tsx when it is not available locally.
Make the file executable:
chmod +x ./file.tsRun it with arguments:
./file.ts hello worldIt prints:
argv: [ 'hello', 'world' ]Global scripts
Use a global installation for scripts that you want to run outside a particular project. The script then depends on the tsx version available in the user's environment.
Install tsx globally and ensure tsx is on your PATH, then save this file in a directory of your choice:
file.ts
#!/usr/bin/env tsx
console.log('argv:', process.argv.slice(2))From that directory, make it executable and run it:
chmod +x ./file.ts
./file.ts hello worldIt prints:
argv: [ 'hello', 'world' ]This hashbang finds tsx through PATH; it does not select a project's local installation.
Troubleshooting
Permission deniedwhen running./file.ts: From the directory containing the file, runchmod +x ./file.tsbefore trying again.- The package manager or
tsxis not found: The command named in the hashbang must be onPATH. For a project script, install the project's dependencies and use its package manager. For a global script, check the global installation setup. - A project script cannot find the local installation: Run it from the project directory, not just from any directory containing the script. The package manager uses the working directory to find project dependencies.
