#How can a .ts file both run from command line and be importable?
11 messages · Page 1 of 1 (latest)
You could run the file with command line arguments. Get the arguments using process.argv. Check if the argument exists before running main function.
A quick internet search on this topic lead me to: https://codewithhugo.com/node-module-entry-required/ -- which seems to answer the question in a short and correct manner
In short using:
if (require.main === module) {
main()
}
seems to be what you looking for.
And for completeness to cite the NodeJS Api Docs about why this works:
Accessing the main module
When a file is run directly from Node.js, require.main is set to its module. That means that it is possible to determine whether a file has been run directly by testing require.main === module.
For a file foo.js, this will be true if run via node foo.js, but false if run by require('./foo').
When the entry point is not a CommonJS module, require.main is undefined, and the main module is out of reach.
Didnt work cause im es6, so I found
import esMain from 'es-main';
if (esMain(import.meta)) {
// The script was run directly.
}
!close
@quiet lily @magic cargo Thank you
I would still advise to have one file for the CLI entry and one file that exports interesting stuff.
Having side-effects (even if they are wrapped by if) will make you lose control over what is happening in your code