`if __name__ == '__main __' 'equivalent in javascript es6 modules

Is it possible to check if the JavaScript file is running directly or if it is required as part of the import of the es6 module.

for example, the main script is included.

// main.js
import './other';

if (mainTest){
  console.log('This should run');
}

which imports the dependency.

// other.js
if (mainTest){
  console.log('This should never run');
}

including <script src=main.js></script>, a console message from main.js, but not other.js should appear .

I found the answer to this question regarding node , but I'm specifically interested in importing es6

+4
source share
2 answers

module.parent will help you:

if(module.parent) {
    console.log('required module')
} else {
    console.log('main')
}
+1
source

, , script. mainTest main.js, if.

0

Source: https://habr.com/ru/post/1624688/


All Articles