Modules

Prior to ES6, JavaScript did not have the notion of modules. Modules are simple code files that can be loaded into the other code so that the functions within the module that is being loaded are made available to the code that is importing the module. Modules can load modules. Modules lead to modular code, and that is a good thing. Rather than write a monolithic bunch of code in one file, you can split it up into logical units and have that code live in more than one file. This leads to code reuse, namespacing, and maintainability.

While JavaScript didn't have modules, we were still able to accomplish the same thing, to a degree. We can load script files with script tags before calling their functions in our web pages. However, what about JavaScript running on the server side, or another environment outside of web pages? Without modules, writing non-monolithic applications becomes difficult. 

let's move on to the code.

Assume we have a file named alphafunctions.js that has the following code in it:

function alpha1() {
console.log("Alpha 1 was called");
}
function alpha2() {
console.log("Alpha 2 was called");
}
export {alpha1, alpha2};

The export keyword is used to mark which functions can be exported and thus imported into other modules.

Let's now assume we have this file, main.js, with the following code:

import {alpha1, alpha2} from ./alphafunctions;  
alpha1(); // "Alpha 1 was called" is written to the console
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.16.184