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).