tsx: TypeScript Execute
tsx (TypeScript Execute) is a command-line interface (CLI) tool that enhances Node.js by providing a seamless way to run TypeScript and ESM files directly, leveraging esbuild for fast transpilation. It allows developers to execute TypeScript without a separate compilation step. The current stable version is 4.21.0. The project is actively maintained with frequent minor releases and bug fixes, often occurring every few weeks.
Common errors
-
Error: The tsx runtime requires Node.js version 18 or higher.
cause The installed Node.js version is below the minimum requirement specified in the package's engines field.fixUpgrade Node.js to version 18.0.0 or newer using a version manager like nvm or volta. -
tsx: command not found
cause The tsx CLI executable is not installed globally or is not accessible in your system's PATH.fixInstall tsx globally via `npm install -g tsx` or execute it using `npx tsx <your-script.ts>`. -
Cannot find module 'some-alias' from '...' or similar module resolution errors.
cause Path aliases defined in tsconfig.json might not be resolved correctly by tsx in some setups, or there's a misconfiguration in module resolution.fixEnsure your `baseUrl` and `paths` are correctly defined in `tsconfig.json`. tsx generally has good path alias support; verify project structure and import paths. -
ReferenceError: require is not defined in ES module scope
cause Attempting to use the CommonJS `require` function within a file that Node.js (and tsx) treats as an ES module.fixConvert `require` statements to `import` statements, or ensure the file is explicitly treated as CommonJS (e.g., by using a `.cjs` extension or setting `type: "commonjs"` in the nearest `package.json`).
Warnings
- gotcha tsx requires Node.js version 18.0.0 or higher. Running with an older version will result in an error.
- gotcha tsx overrides Node.js's native experimental TypeScript loader, meaning its behavior might differ from Node.js's built-in TypeScript execution.
- gotcha tsx uses esbuild for transpilation, which performs no type checking during execution. Type errors in your code will not prevent a script from running.
- gotcha While tsx generally handles tsconfig.json `paths` and `baseUrl`, complex tsconfig configurations or specific `compilerOptions` might not be fully supported by its underlying esbuild transpiler.
Install
-
npm install tsx -
yarn add tsx -
pnpm add tsx
Quickstart
/* my-script.ts */
function greet(name: string) {
console.log(`Hello, ${name}!`);
}
greet('TypeScript');
// To run this:
// npx tsx my-script.ts