-- Main.shssdhakchina - 26 Jan 2022
Modules
As our application grows bigger, we want to split it into multiple files, so called “modules”. A module may contain a class or a library of functions for a specific purpose.
What is a module?
A module is just a file. One script is one module. As simple as that.
Modules can load each other and use special directives export and import to interchange functionality, call functions of one module from another one:
export keyword labels variables and functions that should be accessible from outside the current module.
import allows the import of functionality from other modules.
For instance, if we have a file sayHi.js exporting a function:
// 📁 sayHi.js
export function sayHi(user) {
alert(`Hello, ${user}!`);
}
…Then another file may import and use it:
// 📁 main.js
import {sayHi} from './sayHi.js';
alert(sayHi); // function...
sayHi('John'); // Hello, John!
The import directive loads the module by path ./sayHi.js relative to the current file, and assigns exported function sayHi to the corresponding variable.
Let’s run the example in-browser.
As modules support special keywords and features, we must tell the browser that a script should be treated as a module, by using the attribute <script type="module">.
<!doctype html>
<script type="module">
import {sayHi} from './say.js';
document.body.innerHTML = sayHi('John');
</script>
The browser automatically fetches and evaluates the imported module (and its imports if needed), and then runs the script.
- Modules work only via HTTP(s), not locally
- If you try to open a web-page locally, via file:// protocol, you’ll find that import/export directives don’t work. Use a local web-server, such as static-server or use the “live server” capability of your editor, such as VS Code Live Server Extension to test modules.
Core module features
What’s different in modules, compared to “regular” scripts?
There are core features, valid both for browser and server-side JavaScript.
Always “use strict”
Modules always work in strict mode. E.g. assigning to an undeclared variable will give an error.
<script type="module">
a = 5; // error
</script>
Module-level scope
Each module has its own top-level scope. In other words, top-level variables and functions from a module are not seen in other scripts.
A module code is evaluated only the first time when imported
If the same module is imported into multiple other modules, its code is executed only once, upon the first import. Then its exports are given to all further importers.
In a module, “this” is undefined
That’s kind of a minor feature, but for completeness we should mention it.
In a module, top-level
this is undefined.