Post

ES modules

ES modules

Old way before modules

  • Having just a few variables to think about at one time makes things easier.
  • When you’re working on one function, you can just think about that one function
  • Downside: In JavaScript, functions can’t access variables that are defined in other functions.
  • A common way to share is to put it on a scope above you… for example, on the global scope.

Problem

  • all of your script tags need to be in the right order
  • Any function can grab anything on the global, and mess it up.
js_sharing_global_scope.pngjs_global_scope_issue.png

Solution

es_module_scope.png

  • Modules give you a better way to organize these variables and functions
  • Module scope used to share variables between the functions in the module.
  • Other modules can access the it exported functions/variables
  • This explicit relationship makes it easy to find which modules will break if you remove another one.

How

  • We build up a graph of dependencies, using imports.
  • We provide a file to use as an entry point to the graph.
  • Browser parse all of these files to turn them into data structures called Module Records.
  • Then module record turned into a module instance. An instance = code + state. es_three_phases.png

ES Specs

  • The ES module spec says how you should parse files into module records, and how you should instantiate and evaluate that module.
  • It doesn’t say how to get the files in the first place.
  • It’s the loader that fetches the files. For browsers, that spec is the HTML spec.

Lazy loading

  • With dynamic import, you can use an import statement like import(`${path}/foo.js`).
  • Any file loaded using import() is handled as the entry point to a separate graph.
  • The dynamically imported module starts a new graph, which is processed separately.

CommonJs

  • Uses require()
  • CommonJS can do things differently because loading files from the filesystem takes much less time than downloading across the Internet.
  • This means Node can block the main thread while it loads the file.
  • This also means that you’re walking down the whole tree, loading, instantiating, and evaluating any dependencies before you return the module instance.

CommonJs vs ES modules

  • ES modules use something called live bindings. Both modules point to the same location in memory. where as in commonJS copy is used.
  • In ES module, when the exporting module changes a value, that change will show up in the importing module.

References

This post is licensed under CC BY 4.0 by the author.

Trending Tags