I'm looking for a way to execute function on fly, without saving compiled .js
file
I've tried tsx
and ts-node
, but they run the entire module, so logic has to be in a IIFE way:
(() => {
// ...
})();
Running by script:
tsx <file_path>
Is there any way to make it from IIFE to named exported function and call it like:
tsExcecutor <file_path>/functionName
We can make a script obviously but don't know if you are asking to somehow make IIFE function named that's not possible I guess. But you can make an executor file with a passed function name to execute on the go like that.
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}'.`);
}
and then from command line.
ts-node tsExecutor.ts ./example.ts/myFunction