Modules

JS Modules or ES6 Modules are supported in ES6 version only. However in ES5, some third party libraries add modules support, like CommonJS, AMD based modules in RequireJS and Babel.js

Modules are supported natively in Chrome and Firefox by using exports and import statements.

Module Export

module.js

export var x=33;

Module import

main.js

import x from './module.js';             

Export

Export statement is used to export data from module. We can export single or multiple datatypes using var, let, const or function.

export var


    var age=30;
    export var age;

export let


   export let x=30;

export const


   export const pi=3.14;

export function


    let r=2;
    const pi=3.14;
    
    export function area(){return pi*r*r };

import

import statements is used to import data once export is used. We can import single or multiple data using curly braces with comma separator in import statement.

import is used only inside script with type="module".


<script type="module">    
   import name from './data.js';
   console.log(`name is ${name}.`);
</script>   

import multiple data in export


<script type="module">    
    import {name,age} from './data.js';
    console.log(`name is ${name} and age is ${age}.`);
</script>