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
<script type="module">
  import {x} from './module.js';     
  console.log(`value of x is ${x}`);        
</script>          

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 };

export default

export default is used to export single export value.


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

export multiple

export without default is used to export zero or n number of values.


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

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".

import with default

/*data.js*/


  let name="avinash";
  export default name;

/*index.html*/

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

import multiple data in export

/*data.js*/


export let name="avi";       
export let id=22;
     

/*index.html*/


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