ES Modules
IIFE
A way to make file’s data non-global is to use IIFE:
This way, if we add some JS file to HTML, we’ll not be able to access that JS’s data from the HTML file (encapsulation).
Modules are better for that.
ES6 Modules
Modules characterics:
- they are singletons - every file that imports the module gets the same thing. If something gets modified in exported module by some client, all other clients will see that
- one module is one file
Exporting
There are a few ways to export a module:
Named Export
Contents of myModule.js
OR
Only functionOne
and someValue
get exported. The functionTwo
is not
visible to the clients of this module.
To import it:
We can skip someValue
if we don’t need it.
We can change the name of the exported entity:
Then we’d import it like this:
Export Default
Contents of myModule.js
OR
Only one thing can be exported as default. The client:
The client does not have to know the name of the thing he imports.
Aggregate Exports
One module can export another module, so that the consumer uses just one “import”.
functionThree
is not accessible to that aggreagate module, it just exports it
for the consumers of it (however, it could improt it and make use of it also).
Importing
HTML
Default Import
If module exports something as default, we can import it with any name:
Named Import
We can change name in the client:
We can import all that was exported:
Mixed Import
OR