Modules Flashcards

1
Q

What are modules and how are they different from regular javascript scripts?

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are some browser-specific features of modules?

A
  1. Module scripts are deferred by default - so they can always access the full loaded html
  2. Async works on inline scripts
  3. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the role of module build tools?

A

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:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly