创建既是命令行实用程序又是导出方法的 npm TypeScript 模块——这可能吗?

Create npm TypeScript module that is both command line utility and exports methods - is it possible?

我想创建 npm TypeScript 模块,它既可以用作命令行实用程序,也可以用作其他模块中使用的导出方法。

问题是命令行实用程序模块需要在 index.ts 的第一行包含节点 shebang(#!/usr/bin/env 节点)。当在另一个模块中导入并引用此类模块时,代码在实际调用任何导出的方法之前开始执行。示例:

#!/usr/bin/env node

const arg1: number = parseFloat(process.argv[2]);
const arg2: number = parseFloat(process.argv[3]);

console.log (superCalc(arg1, arg2)); // this gets called when superCalc() is referenced in another module

export function superCalc(arg1: number, arg2: number) : number {
    return arg1 + arg2;
}

您可以将源代码放在不同的文件中并允许从该文件导入。例如:

src/index.ts

export function superCalc(arg1: number, arg2: number) : number {
    return arg1 + arg2;
}

src/cli.ts

#!/usr/bin/env node

const arg1: number = parseFloat(process.argv[2]);
const arg2: number = parseFloat(process.argv[3]);

console.log (superCalc(arg1, arg2));

package.json

{
  // Additional settings
  "bin": { "your-script": "./dist/cli.js" },
  "main": "dist/index.js",
}

现在用户可以执行 CLI (npm run your-script),但也可以通过 import { superCalc } from "your-package"index.js 导入(假设您正在编译用于分发的 TypeScript)。这不包括导出方法的示例,但是 more details on creating a CLI with TypeScript.