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

JavascriptEcmascript 6Es6 Modules

Javascript Problem Overview


Does the code inside the js file gets run during the import? if yes, then once or each time? e.g.

// a.js
console.log("A");
const a = "a"; 
export default a;

// b.js
import a from "./a"; // => console logs?

// c.js
import a from "./a"; // => console logs again?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmbehzadView Question on Stackoverflow
Solution 1 - Javascriptuser663031View Answer on Stackoverflow
Solution 2 - JavascriptandyhasitView Answer on Stackoverflow
Solution 3 - JavascriptLeon TepeView Answer on Stackoverflow