如何在nodejs脚本中从TypeScript文件调用函数?

问题描述 投票:0回答:1

我正在寻找一种即时执行函数的方法,而不保存编译的

.js
文件

我尝试过

tsx
ts-node
,但它们运行整个模块,所以逻辑必须采用IIFE方式:

(() => {
  // ...
})();

通过脚本运行:

tsx <file_path>

有什么方法可以将其从 IIFE 转换为命名导出函数并像这样调用它:

tsExcecutor <file_path>/functionName
node.js typescript npm-scripts
1个回答
0
投票

我们显然可以制作一个脚本,但不知道您是否要求以某种方式命名 IIFE 函数,我猜这是不可能的。但是您可以使用传递的函数名称创建一个执行程序文件,以便像这样随时执行。

const [, , command] = process.argv;
const [filePath, functionName] = command.split('/');
const modulePath = path.resolve(filePath);
const module = require(modulePath);

if (typeof module[functionName] === 'function') {
  const functionToExecute = module[functionName];
  (() => {
    functionToExecute();
  })();
} else {
  console.error(`Function '${functionName}' not found in '${filePath}'.`);
}

然后从命令行。

ts-node tsExecutor.ts ./example.ts/myFunction
© www.soinside.com 2019 - 2024. All rights reserved.