Modules in JavaScript ES6

 Modules are the piece or chunk of a JavaScript

code written in a file. JavaScript modules help us to modularize the code simply by partitioning the entire code into modules that can be imported from anywhere. Modules make it easy to maintain the code, debug the code, and reuse the piece of code. Each module is a piece of code that gets executed once it is loaded.




Exporting a Module

JavaScript allows us to export a function, objects, classes, and primitive values by using the export keyword. There are two kinds of exports:

  • Named Exports: The exports that are distinguished with their names are called as named exports. We can export multiple variables and functions by using the named export.
  • Exporting Function , variable , class from library.js


        export var name = "this is first variable vaues";


        export function msg(){
            console.log("this is function ")
        }


        export class text{
            constructor(){
                console.log("Constructor Method");
            }
        }
       

Importing a Module, into main.js

To import a module, we need to use the import keyword. The values which are exported from the module can be imported by using the import keyword. We can import the exported variables, functions, and classes in another module. To import a module, we simply have to specify their path.

When you import the named export, you must have to use the same name as the corresponding object. When you import the default export, we can use any name of the corresponding object.

 
    import {name, msg, text} from './library.js';

    console.log(name);
    msg();

    var a = new text();