https://medium.freecodecamp.org/javascript-modules-a-beginner-s-guide-783f7d7a5fcc
Module is a standalone file that contains reusable pieces of code that encapsulates implementation details.
In other words, they are small building blocks that we put together to build complex applications.
Modules make it easy to abstract code. We use it to implement low level code. Other modules then import these abstractions and use them.
It does this through exporting values out of modules. If it needs other functionalities, it can import it from other modules.
These other modules are called dependencies.
Modules allow us to easily reuse code. If we need same functionalities, we just copy module to new projects.
As of es6, JS have a native module system.
1 module per file.
1) In modules, all variables are scoped only to the module. This offers a great way to encapsulate. The only way other modules can access data inside this module, it must import this module.
Whereas in a script, these variables would be considered to be global.
2) Module are executed in strict mode This means, the ‘this’ keyword is always undefined
In scripts, its sloppy mode and this references the global/window object.
3) Imports are hoisted. So no matter where you import, they are hoisted to the top.
4) In HTML, if we want to use a module, we must use
1 |
<script type="module">...</script> |
instead of the script way:
1 |
<script>....</script> |
First we parse index.js
From the parsing we see that we need to import rand from math module. And showDice from the module.
We download and import all imported modules before execution. Module imports are synchronous.
Module downloads are asychronous.
We then link imports to math.js exports and dom.js exports.
Execute math.js and dom.js
Then finally, we can execute our index.js