What is a module?
In JavaScript, the word “modules” refers to small units of independent, reusable code. They are the foundation of many JavaScript design patterns and are critically necessary when building any substantial JavaScript-based application.
In simpler terms, modules help you to write code in your module and expose only those parts of the code that should be accessed by other parts of your code.
JavaScript has had modules for a long time. However, they were implemented via libraries, not built into the language. ES6 is the first time that JavaScript has built-in modules.
- Each module is a piece of code that is executed once a JavaScript file is loaded.
- In that code, there may be declarations (variables, functions, classes e.t.c).
- By default, every declaration in that file stay local to that module and cannot be accessed in other modules unless the module file exports them.
What are ES6 Modules?
Before now, it was impossible to directly reference or include one JavaScript file in another, as such, developers therefore resorted to alternative options like multiple HTML script tags.
This is a bad practice as each script initiates a new HTTP request, which affects page performance and disrupts further processing while it runs.
<script src="app.js"></script>
<script src="search.js"></script>
<script src="user.js"></script>
<script>
console.log('inline code');
</script>
This is a bad practice as each script initiates a new HTTP request, which affects page performance and disrupts further processing while it runs.
Let's say we have a file, app.js and included in this file is a function which checks every limit in a number and returns if it’s EVEN or ODD.
function showNumbers(limit) {
for (let i = 0; i <= limit; i++) {
const message = (i % 2 === 0) ? 'EVEN' : 'ODD';
console.log(i, message);
}
}
Now this function is only available within app.js . Wherever you need this function, you have to either rewrite the function or attach the script again. This is where ES6 Modules come in.
With ES6 modules, you can concatenate all scripts in one main script by marking some of them as exports, then other modules can import them.
// name.js
function displayName(name) {
alert(`Hello, ${name}!`);
}
class User {
constructor(name) {
this.name = name;
}
}
export {displayName, User};