How do I write a Node script that can be run from either the mand 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 mand line:
node --experimental-modules sayHello.mjs
Via 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 mand line');
} else {
console.log('required as a module');
}
How do I write a Node script that can be run from either the mand 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 mand line:
node --experimental-modules sayHello.mjs
Via 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 mand line');
} else {
console.log('required as a module');
}
Share
Improve this question
edited Jun 4, 2020 at 3:58
Sergey Vyacheslavovich Brunov
18.2k7 gold badges52 silver badges85 bronze badges
asked Sep 20, 2018 at 17:55
dwhiebdwhieb
1,84620 silver badges31 bronze badges
1 Answer
Reset to default 4You could try:
function sayHello() { console.log("Hello"); }
if (process.env.CL == 1){
sayHello();
} else {
export default sayHello;
}
From mandline, use:
CL=1 node --experimental-modules sayHello.mjs
Pretty simple, but it should work
Another option is to check process.argv[1]
since it should always be the filename that was specified from the mandline:
if (process.argv[1].indexOf("sayHello.mjs") > -1){
sayHello();
} else {
export default sayHello;
}