2

I have been working with ES6 modules, and I was looking for a way to include code that runs only if the file is executed directly (as opposed to being imported by another file). In languages like Python that have had earlier native module support, this is easy: simply wrap the code in a if __name__ == '__main__' block and the code will only run if the file is executed directly. This is quite useful for things like attaching basic testing code to a library. I am curious if there is any way to do this with ES6.

Ideally, I would like to have something like this:

File a.js

export const pi = 3.1415
/* Some magical code here */
console.log("This only prints if you run a.js directly.")

File b.js

import {pi} from 'a';
console.log(pi);

So that one could execute the files and get the following outputs:

> somejsengine ./a.js
"This only prints if you run a.js directly."
> somejsengine ./b.js
3.1415

I am also curious if such a solution exists for Node's CommonJS modules (as Node.js still doesn't support ES6 style modules).

Community
  • 1
  • 1
Shrey Gupta
  • 5,509
  • 8
  • 45
  • 71
  • You mean [How to have a CommonJS module execute its main() (as in Python)?](http://stackoverflow.com/q/6129829/218196) There is nothing in ECMAScript itself that provides such a functionality. Any solution you are looking for is environment specific (I guess Node.js in your case). – Felix Kling May 20 '17 at 00:06
  • There's no way, and the way it should be done in Node depends on what exactly 'attaching basic testing code to a library' means. This is XY problem, the question should reflect real problem in order to get an answer that can solve it. – Estus Flask May 20 '17 at 09:06

1 Answers1

1

Actually there is a possibility for this in Node: Accessing the main module

You can check, if the module is run directly with require.main === module.

if (require.main === module) {
    console.log("This only prints if you run a.js directly.")
}