- A module is just a file or a single script.
- There are directives
export
and import
to interchange functionality between modules and call functions of one module from another one:
export
keyword labels variables and functions that should be accessible from outside the current module.
// 📁 sayHi.js
export function sayHi(user) {
alert(`Hello, ${user}!`);
}
- We can also put
export
separately (above or below the declaration).
// 📁 say.js
function sayHi(user) {
alert(`Hello, ${user}!`);
}
function sayBye(user) {
alert(`Bye, ${user}!`);
}
export {sayHi, sayBye}; // a list of exported variables
import
allows to import functionality from other modules.
// 📁 main.js
import { sayHi, sayBye } from './say.js';
sayHi('John'); // Hello, John!
sayBye('John'); // Bye, John!
- We can also import everything:
// 📁 main.js
import * as say from './say.js';
say.sayHi('John');
say.sayBye('John');
- As modules support special keywords and features, we must tell the browser that a script should be treated as module, by using the attribute
<script type="module">
.
<script type="module">
import {sayHi} from './say.js';
document.body.innerHTML = sayHi('John');
</script>
export as
// 📁 say.js
export {sayHi as hi, sayBye as bye};
import as
// 📁 main.js
import { sayHi as hi, sayBye as bye } from './say.js';
hi('John'); // Hello, John!
bye('John'); // Bye, John!
export default
- Modules provide special
export default
syntax to make “one thing per module” way look better.
- It requires following
export
and import
statements:
- Put
export default
before the “main export” of the module.