Narayan Prusty
Narayan Prusty

Reputation: 427

ES6 Modules are loaded Synchronously or Asynchronously?

Module loader is responsible for loading modules.

What I know is module loader loads modules in browser asynchronously whereas in Node.js it loads synchronously.

I wanted to confirm whether this information is correct or not.

Upvotes: 13

Views: 7011

Answers (2)

Ian Carter
Ian Carter

Reputation: 1063

ESM is intentionally async (to accomodate loading over networks) and the rationale behind import also aims at knowing during code interpretation what dependencies exist (e.g. allowing bundlers to do treeshaking etc). This is also the reason to have imports at the beginning of your files and they can't be conditional (unless you use the await import() syntax).

You can also not eval(readFileSync(moduleFile)) if you use ESM syntax in the loaded file.

Upvotes: 0

Endre Simo
Endre Simo

Reputation: 11551

ES6 module loaders will be asynchronous while node.js module loaders are not.

Here are some key aspects of module loaders:

  • Module code automatically runs in strict mode and there’s no way to opt-out of strict mode.

  • Variables created in the top level of a module are not automatically added to the shared global scope. They exist only within the top-level scope of the module.

  • The value of this in the top level of a module is undefined. Does not allow HTML-style comments within the code (a leftover feature from the early browser days).

  • Modules must export anything that should be available to code outside of the module.

https://leanpub.com/understandinges6/read#leanpub-auto-modules

Modules, in general, solve several problems for developers. First, they allow the developer to separate code into smaller pieces, called modules. Second, they make it easy for developers to load (inject) those modules into other sections of code. Having modules injected like this helps keep project code uncoupled from the module (read: improved testability). And third, modules can load scripts asynchronously. This means that apps can begin loading faster, as they don’t require all scripts to be loaded prior to executing code.

http://chimera.labs.oreilly.com/books/1234000001623/ch03.html#_default_values

On the other hand because node.js is based on require which is synchronous this means node.js does not provide an asynchronous variant out of the box.

Of course there are async module loaders for node (async-require), but natively (with require) is not supported.

Upvotes: 11

Related Questions