#How can a .ts file both run from command line and be importable?

11 messages · Page 1 of 1 (latest)

bold compass
#

I have a .ts with

function doX(){}

and at bottom I have

const main = async () => { doX()}
main() 

However, if I import this file into another ts then main runs. So do I need yet another file to accomplish my goal of both running from command line and be importable?

magic cargo
#

You could run the file with command line arguments. Get the arguments using process.argv. Check if the argument exists before running main function.

quiet lily
#

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.
bold compass
#

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

south lantern
#

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