返回

从零开始发布 TypeScript 开发的 Node.js 命令行工具

前端

简介

在上篇文章中,我们使用 TypeScript 和百度翻译 API 编写了一个 Node.js 命令行工具(使用 commander.js)。该工具可以将传入终端的文本翻译成目标语言。现在,让我们更进一步,将此工具发布到 npm,以便其他人也能使用它。

步骤

1. 设置项目

首先,确保你已经安装了 Node.js 和 npm。然后,创建一个新的文件夹,用于存储你的项目,并导航到该文件夹。

2. 初始化 npm 项目

在项目文件夹中,运行以下命令初始化一个新的 npm 项目:

npm init -y
3. 安装依赖项

接下来,我们需要安装用于构建和测试命令行工具的依赖项:

npm install commander typescript @types/commander
4. 创建 TypeScript 配置文件

创建一个名为 tsconfig.json 的文件,并添加以下内容:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "./dist"
  }
}
5. 编写命令行工具

创建名为 cli.ts 的 TypeScript 文件,并粘贴以下代码:

import { program } from 'commander';

program
  .name('ts-node-dev')
  .version('1.0.0')
  .description('Translate text using the Baidu Translate API')
  .option('-l, --language <language>', 'Target language (default: "zh")')
  .argument('<text>', 'Text to translate')
  .action((text, options) => {
    // ...
  });

program.parse(process.argv);
6. 构建命令行工具

使用以下命令构建你的命令行工具:

tsc
7. 创建 package.json 文件

创建 package.json 文件,并添加以下内容:

{
  "name": "ts-node-dev",
  "version": "1.0.0",
  "description": "Translate text using the Baidu Translate API",
  "main": "dist/cli.js",
  "scripts": {
    "start": "ts-node-dev src/cli.ts"
  },
  "keywords": [
    "typescript",
    "nodejs",
    "command-line-tool",
    "baidu-translate"
  ],
  "author": "Your Name",
  "license": "MIT"
}
8. 发布到 npm

最后,使用以下命令将你的工具发布到 npm:

npm publish

结论

恭喜!你已经成功地将 TypeScript 开发的 Node.js 命令行工具发布到了 npm。现在,其他开发人员可以在他们的项目中使用你的工具了。