TIL what ES modules are
POSTED ON:
TAGS: javascript
What are they #
ES Modules (ESM) is the official, standardize module system to Javascript.
Remember how jQuery would just throw every function/variable into the global space? And if you accidentally loaded a function after when jQuery needs it, it crashes the program?
Modules give you a better way to organize these variables and functions. With modules, you group the variables and functions that make sense to go together.
If your website application needs a hundred files, you don't want that jQuery problem.
So using ES Modules, you can import/export
the snippets you need, when you need them.
In CommonJS and Node, we install libraries and then import/export
them into our projects. Installs can take 1 second or 10 minutes. It downloads the whole library directly to our computer. Then a compiler (like webpack) smartly tries to figure out when to use what snippets/code blocks you need to get it working.
On the web, we can't use CommonJS. It'll just bottleneck everything, as the user waits for things to start compiling and working.
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. And since the file is already loaded, it makes sense to just instantiate and evaluate (which aren’t separate phases in CommonJS). This also means that you’re walking down the whole tree, loading, instantiating, and evaluating any dependencies before you return the module instance.
ES Module Loading is the solution. There's 3 steps:
-
Construction — find, download, and parse all of the files into module records.
-
Instantiation — Start creating all the memory needs.
-
Evaluation — Start using the code we set up in memory.
Explain like i'm 5 #
In the early days of the internet, you only need a little script here or there. Now we have complete applications running in the browser. As Javascript became more complicated, we needed a way to organize it. In Node, you do that with the import
statement. You npm i
a library, import into your program, and you're set.
The web needs something like that too. But for big applications, do we expect the user to download 100megs of a library, just to use your website? ES Modules is that solution. It has 3 steps that it follows. At the end, it cherry picks exactly the code it needs from all the right places.
How to use it #
<script type="module">
import { appendResult } from "./myModule.js";
const el = document.getElementById("el");
appendResult(el);
</script>
import toUpperCase from 'https://flavio-es-modules-example.glitch.me/uppercase.js'
import { toUpperCase } from '/uppercase.js'
import { toUpperCase } from '../uppercase.js'
REFERENCES:
ES modules: A cartoon deep-dive
and https://flaviocopes.com/es-modules/
Related TILs
Tagged: javascript