CommonJS vs ES Modules

Viewed 1209

Could someone explains why CommonJS is dynamic, while ES is static? And what is dynamic and static mean in this context? And also I am quite confused about the difference between parse time and run time, hope someone could also explain that a little. Thanks!

1 Answers

It's pedantic to say "parse time", as this refers to the time before running the app, normally called compile time. Modules allow some code to be examined and mapped in relation to each modules' file location, imports, and exports, before it is run - at "parse time". Before a single function is run, each function is parsed, meaning its name and other properties are assembled such that other modules may import them. The result of function calls and the value of variables at this point is unknown but the function per se is known.

When importing using ES the variables, functions, etc that are imported are not normally dynamically assembled (there is a partly implemented proposal documented here), which happens at run time. Using ES the program explicitly states the dependencies regardless of any program variance. Importing in different order doesn't matter. Regardless of the soundness or lack thereof of the imported code the result is the same - i.e. static and the import statement is correct or incorrect before any of the code is evaluated to any value.

Because CommonJS evaluates more of the code at once than ES, more is known if followed in a sequential way. One of the implications is that code within the string of a require statement can have variables, making the statement dynamic, but ES cannot. ES exports are parsed but the entire module is not available to other modules that import it at the time the import statement is evaluated.

There is an MDN article that explains this more thoroughly.

Related