Java script module

Module are just file, enable to reuse of code.
 
Module uses directive.
  • export
    export enable to export code to other file.
  • import
    import enable to import code from other file.
 
There are different ways to use java script modules.
One of the popular way to use with node js with package.json file and must have attribute type : "module"
 
package.json

{ "name": "es6", "version": "1.0.0", "description": "", "main": "data.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "type":"module" }
 

Export, import variable

 
data.js
export let company="CAPSCOM"
 
home.js
import {company} from './data.js'

Export, import array

data.js
export let products=["Mobile", "TV", "Mouse"];
 
home.js
import {products} from './data.js'
 

Export, import object

data.js
let person={
name:"Ajay",
age: 20
}

export person;
 
home.js
import {person} from './data.js'
 

Export, import function

data.js
let sum=(a, b)=>a+b;
export sum;
 
home.js
import {sum} from './data.js'

Module as single task.

default
 
data.js
let sum=(a, b)=>a+b;
export default sum;
 
home.js
import sum from './data.js'
© 2016 - 2022, All Rights are Reserved.