我正在寻找一种即时执行函数的方法,而不保存编译的
.js
文件
我尝试过
tsx
和ts-node
,但它们运行整个模块,所以逻辑必须采用IIFE方式:
(() => {
// ...
})();
通过脚本运行:
tsx <file_path>
有什么方法可以将其从 IIFE 转换为命名导出函数并像这样调用它:
tsExcecutor <file_path>/functionName
我们显然可以制作一个脚本,但不知道您是否要求以某种方式命名 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