Is it possible to check if JavaScript file is being run directly or if it was required as part of an es6 module import.
for example a main script is included.
<module.parent will help you:
if(module.parent) {
console.log('required module')
} else {
console.log('main')
}
The solution I see there is just to define the variable in the script you're importing. I.e. you define mainTest
in main.js
, and then use your existing if block.
An alternative for ES6 modules is now supported in Node. Using the new import.meta
builtin.
Example:
// main.mjs
import { fileURLToPath } from "url";
import "./lib.mjs"
if (process.argv[1] === fileURLToPath(import.meta.url)) {
console.log(`main ran!`);
}
// lib.mjs
import { fileURLToPath } from "url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
console.log(`lib ran!`);
}
and our output:
main ran!