Does ES6 module importing execute the code inside the imported file?

A module will only be evaluated once but it is possible to have two copies of the same module installed in a project, in which case that module and the code in it will be executed twice.

Consider the following package structure:

index.js
package.json
node_modules/
├── package_b/
│   └── node_modules/
│       └── package_a/
|           └── index.js
└── package_c/
    └── node_modules/
        └── package_a/
            └── index.js

If the top level index.js imports from package_b and package_c, then package_a will be imported (and therefore evaluated) twice.

Most people are not aware of this behaviour yet probably need to be if they landed on this particular question.

Here is an old but good article on understanding-the-npm-dependency-model with further detail on how and why npm does this.


In case someone is using TypeScript with "module": "es6" and wondering how to do this, use the globalThis keyword:

function outputMsg(msg: string) : void {
    console.log(msg);
}

// export function for global scope
globalThis.outputMsg = outputMsg;

and then call outputMsg("my console output") as usual in the Chrome DevTools console and it should autocomplete and run your function.

You could also rename your "global export":

globalThis.myCrazyFunc = outputMsg;

and call myCrazyFunc("crazy message") in the console.


Yes, it does, exactly one time.

See http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-module-records:

Do nothing if this module has already been evaluated. Otherwise, transitively evaluate all module dependences of this module and then evaluate this module