Building a CLI Tool with TypeScript
Creating a Command-Line Interface (CLI) tool with TypeScript provides type safety and modern JavaScript features. TypeScript enhances the development experience by offering static typing and better tooling support. This guide covers the steps to build a CLI tool using TypeScript.
Step 1: Set Up Your TypeScript Project
Begin by setting up a new TypeScript project. Initialize a new npm project and install TypeScript and other dependencies.
npm init -y
npm install typescript ts-node @types/node --save-dev
npx tsc --init
The ts-node
package allows for running TypeScript files directly, while @types/node
provides type definitions for Node.js.
Step 2: Create a Basic CLI Script
Create a TypeScript file that will serve as the entry point for the CLI tool. This file will handle the command-line arguments and implement the core functionality.
import { Command } from 'commander';
const program = new Command();
program
.version('1.0.0')
.description('A simple CLI tool')
.option('-n, --name <name>', 'Specify the name')
.action((options) => {
console.log(`Hello, ${options.name || 'World'}!`);
});
program.parse(process.argv);
Here, the commander
package is used to handle command-line arguments and provide a simple interface for defining commands and options.
Step 3: Add CLI Dependencies
Install additional dependencies required for building the CLI tool. For this example, commander
is used for argument parsing.
npm install commander
Step 4: Compile TypeScript Code
Compile the TypeScript code into JavaScript. This step is necessary for distributing the CLI tool.
npx tsc
Step 5: Create an Executable Script
Update the package.json
file to include a bin
section. This section maps the CLI command to the compiled JavaScript file.
{
"name": "my-cli-tool",
"version": "1.0.0",
"bin": {
"my-cli-tool": "./dist/index.js"
},
"scripts": {
"build": "tsc",
"start": "ts-node src/index.ts"
},
"dependencies": {
"commander": "^8.3.0"
},
"devDependencies": {
"@types/node": "^14.14.31",
"typescript": "^4.3.5",
"ts-node": "^10.2.1"
}
}
Step 6: Test Your CLI Tool
Link the CLI tool locally to test it before publishing. Use npm link
to create a symlink in the global node_modules
directory.
npm link
my-cli-tool --name TypeScript
Conclusion
Building a CLI tool with TypeScript involves setting up a TypeScript project, creating a basic CLI script, adding dependencies, and compiling the code. By leveraging TypeScript’s static typing and modern features, it’s possible to create robust and maintainable CLI tools.