Modules Flashcards
What are modules and how are they different from regular javascript scripts?
Modules are just javascript files.
Modules can load each other and use special directives export and import to interchange functionality, call functions of one module from another one:
<script> import {sayHi} from './say.js'; document.body.innerHTML = sayHi('John'); </script>
They differ from regular scripts in:
1. use strict by default
2. module-level scope: top-level variables are isolated from other modules
3. module code is only evaluated only the first time it is imported
// 📁 alert.js
alert(“Module is evaluated!”);
// 📁 1.js
import ./alert.js
; // Module is evaluated!
// 📁 2.js
import ./alert.js
; // (shows nothing)
4. ‘this’ is undefined(where it is window in non-module scripts)
What are some browser-specific features of modules?
- Module scripts are deferred by default - so they can always access the full loaded html
- Async works on inline scripts
- External scripts:
- External scripts with the same src run only once:
- External scripts that are fetched from another origin (e.g. another site) require CORS headers, as described in the chapter Fetch: Cross-Origin Requests. In other words, if a module script is fetched from another origin, the remote server must supply a header Access-Control-Allow-Origin allowing the fetch.
What is the role of module build tools?
One of the benefits of using bundlers – they give more control over how modules are resolved, allowing bare modules and much more, like CSS/HTML modules.
Build tools do the following:
1. Take a “main” module, the one intended to be put in
in HTML.
2. Analyze its dependencies: imports and then imports of imports etc.
3. Build a single file with all modules (or multiple files, that’s tunable), replacing native import calls with bundler functions, so that it works. “Special” module types like HTML/CSS modules are also supported.
4. In the process, other transformations and optimizations may be applied:
- Unreachable code removed.
- Unused exports removed (“tree-shaking”).
- Development-specific statements like console and debugger removed.
- Modern, bleeding-edge JavaScript syntax may be transformed to older one with similar functionality using Babel.
- The resulting file is minified (spaces removed, variables replaced with shorter names, etc).
If we use bundle tools, then as scripts are bundled together into a single file (or few files), import/export statements inside those scripts are replaced by special bundler functions. So the resulting “bundled” script does not contain any import/export, it doesn’t require type=”module”, and we can put it into a regular script: