ECMAScript question detail
Modules
Modules are small units of independent, reusable code to be used as the building blocks in a Javascript application.
Prior to ES6, there was no native modules support in JavaScript. There were 3 major module standards used,
- Asynchronous Module Definition (AMD)
- RequireJS Modules
- CommonJS Modules (module.exports and require syntax used in Node.js)
ES6 has provided the built-in support for modules. Everything inside a module is private by default, and runs in strict mode. Public variables, functions and classes are exposed using export statement and import the same using import statement.
Export Statement:
There are two types of exports:
- Named Exports (Zero or more exports per module)
You can export each element or a single export statement to export all the elements at once
// module "my-module.js"
const PI = Math.PI;
function add(...args) {
return args.reduce((num, tot) => tot + num);
}
function multiply(...args) {
return args.reduce((num, tot) => tot * num);
}
// private function
function print(msg) {
console.log(msg);
}
export { PI, add, multiply };
- Default Exports (One per module)
If we want to export a single value, you could use a default export
// module "my-module.js"
export default function add(...args) {
return args.reduce((num, tot) => tot + num);
}
Import Statement:
The static import statement is used to import read only live bindings which are exported by another module.
There are many variations of import scenarios as below,
// 1. Import an entire module's contents
import * as name from "my-module";
//2.Import a single export from a module
import { export1 } from "my-module";
//3.Import multiple exports from a module
import { export1 , export2 } from "my-module";
//4.Import default export from a module
import defaultExport from "my-module";
//5.Import an export with an alias
import { export1 as alias1 } from "my-module";