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 defaul
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
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.
Actually that depends on where those modules are. If those are all in the same project then the code in a.js will indeed run once. But if a.js, b.js and c.js are in 3 separate packages then the code in a.js could run more than once.
E.g. if you list package_b and package_c as dependencies in your project and both of those list package_a as a dependency, then the code will run twice.
That's because npm installs two separate copies of package_a - one for package_b and one for package_c:
node_modules/
├── package_b/
│ └── node_modules/
│ └── package_a/
| └── a.js
└── package_c/
└── node_modules/
└── package_a/
└── a.js
So yes, the code in the module technically runs once, but you have two separate copies of the module, which each get imported once.
I think this is a worthy answer as people landing on this question are unlikely to be aware of this, yet probably very much need to be if they landed on this question (especially given how badly wrong things will go thinking it works just like Ruby or Python).
Here is an old but good article on understanding-the-npm-dependency-model with further detail on how and why npm does this.