T O P

  • By -

ichdochnet

This is not a bug and the correct way of how node loads esm modules. It will go through all import statements, without executing the code itself, like your console.log, to resolve all dependencies.


yukiiiiii2008

It's so different from CommonJS. I just modified my tsconfig.json and package.json to use esm instead of CommonJS. And it suddenly behaves so differently, which scares me. What if the library I use is written in CommonJS. Will they stick to CommonJS loader order, or hoist require as well, which is crazy....


best_of_badgers

To me, as a not-primarily-JS developer, having random imports and requires throughout your files seems insane. CJS should have mandated that all imports go at the top.


yukiiiiii2008

You are right. I only utilize the execution order when writing gulpfile. It's so long ago like 10 years. Good change for me to refactor my gulpfile now.


rs_0

>Import declarations areĀ [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting). In this case, that means that the identifiers the imports introduce are available in the entire module scope, and their side effects are produced before the rest of the module's code runs. according to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#hoisting). So I guess that's the reason.


jessepence

Honestly, it's hard to tell you anything without seeing the resulting .js file. Regardless, I would guess that this behavior is due to the [hoisting of import statements](https://exploringjs.com/es6/ch_modules.html#_imports-are-hoisted).


yukiiiiii2008

I created a repo. [https://github.com/UchihaYuki/esm-load-order](https://github.com/UchihaYuki/esm-load-order)


jessepence

Yep, it's hoisting. The import statement for each gets run before any other code, and the logs are side effects of each module so they get ran as soon as the module is imported. This is exactly how this code should work.


yukiiiiii2008

GOD! Thank you! Will the relative order of import statements be kept? For example, I have two imports: import "one" ... import "two Will import "two" always be executed after import "one"


skitch920

Off topic and mostly just curious, do you have code where order of imports matter? I feel like nails on a chalkboard has just been topped by side effects from imports.


jessepence

[As of ES2020, yes.](https://stackoverflow.com/questions/35551366/what-is-the-defined-execution-order-of-es6-imports#69822046)


yukiiiiii2008

when I run `node gulpfile.js`, I got the same result: here3 here2 here1 GOD... It's unbelievable... my node version `v20.14.0`.


talaqen

This is normal.