ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import
and export
statements.
- Case One:
import * as lib from "./lib.js";
- Case Two:
import { addFive, addTwo, mobile } from "./lib.js";
- Case Three:
import { default as main } from "./libtwo.js";
- Case Four:
import hello from "./libtwo.js";
const addFive = function (n) {
return n + 5;
};
function addTwo(n) {
return n + 2;
}
const mobile = {
Samsung: "Galaxy",
Apple: "iPhone",
};
export { addFive, addTwo, mobile };
function Hello() {
return "Hello World";
}
const banana = {
color: "Yellow",
};
const addFive = function (n) {
return n + 5;
};
export default Hello;
export { addFive, banana };
import * as lib from "./lib.js";
import { addFive, addTwo, mobile } from "./lib.js";
import { default as main } from "./libtwo.js";
import hello from "./libtwo.js";
import * as libtwo from "./libtwo.js";
import { banana } from "./libtwo.js";
// Get all functions or object from lib.js
console.log("========================");
console.log(lib.addFive(5));
console.log(lib.addTwo(5));
console.log(lib.mobile.Apple);
console.log(lib.mobile.Samsung);
// Get some functions or object from lib.js
console.log("========================");
console.log(addFive(5));
console.log(addTwo(5));
console.log(mobile.Apple);
console.log(mobile.Samsung);
// Use export default from libtwo.js
console.log("========================");
console.log(hello());
console.log(main());
console.log(libtwo.default());
// Get all functions or object from lib.js
console.log("========================");
console.log(libtwo.addFive(3));
console.log(libtwo.banana.color);
// Get a object from libtwo.js
console.log("========================");
console.log(banana.color);
========================
10
7
iPhone
Galaxy
========================
10
7
iPhone
Galaxy
========================
Hello World
Hello World
Hello World
========================
8
Yellow
========================
Yellow
In package json.
{
"name": "es6",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
Without package JSON, if your file extension is .mjs, the ECMAScript modules will work.
When calling up multiple named exports, the ECMAScript module allows you to selectively use only the objects you need globally, or nickname all objects and access them through them.