1

If I import a module A inside both module B and C, is the code inside A executed 2 times in total? That means if I call fetch() inside A, will fetch() be called 2 times?

e.g.

//file: A.js
var A = {
  init: false,
  count: 0
};

if(A.init == false) {
  A.init = true;
  A.value = fetch("https://...");
}

I thought module codes are only executed once for the lifetime of the webpage no matter how many times they are imported?

So if inside module B I set A.count = 1, then inside module C, the value of A.count is also 1.

But according to "Import a module for its side effects only" at:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

I can run a module A code multiple times for each module (B, C, D) that uses it. How does this commensurate with the above?

Kernel James
  • 3,752
  • 25
  • 32

1 Answers1

-3

The code from Module A will be executed 2 times! Once in Module B and again in Module C.

Module A

function foo() {
  return 'yo I`m in module A being executed in... ';
}

export default foo;

Module B

import foo from './moduleA';

console.log(`${foo()} in module B`);

Module C

import foo from './moduleA';

console.log(`${foo()} in module C`);
Amechi
  • 742
  • 3
  • 11
  • 32
  • 3
    The question is about ESM `import`, not `require`. In any case, [per Node spec](https://nodejs.org/api/modules.html#caching), "every call to require('foo') will get exactly the same object returned, if it would resolve to the same file" and "multiple calls to require('foo') will not cause the module code to be executed multiple times. This is an important feature." – Inigo Jan 05 '22 at 09:05
  • @kernel-james, not sure why you accepted this answer (and down-voted mine) as it is flat wrong, as I noted above and also as clearly shown in the question that yours is a duplicate of. ‍♂️ – Inigo Jan 05 '22 at 19:35
  • @Inigo check this [answer](https://stackoverflow.com/questions/37325667/does-es6-module-importing-execute-the-code-inside-the-imported-file). Node has a bit of quirk. – Amechi Jan 06 '22 at 13:13
  • 2
    Your answer is still very wrong. (1) your sample code does not even show that the code in the `Module A` file runs twice (calling `foo()` twice does not count), (2) this so-called "quirk" you refer to is for `npm`, not for ESM. See my comment at your link. – Inigo Jan 07 '22 at 04:21