How do I write a Node script that can be run from either the command line or via an ES6 import statement?
I am using the --experimental-modules flag and .mjs extension to run scripts as ES6 modules.
Example
Say I have the following script in sayHello.mjs:
export default function sayHello() {
console.log(`Hello!`);
}
I would like to be able to use this script in the following two ways:
Via the command line:
node --experimental-modules sayHello.mjsVia an ES6 import statement in another script:
import sayHello from './sayHello.mjs'; sayHello();
Details
I am looking for a solution similar to using module.main for CommonJS modules (this does not work for ES6 imports):
if (require.main === module) {
console.log('run from command line');
} else {
console.log('required as a module');
}