ECMAScript 6 modules
By what we have seen so far, organizing our JavaScript code in modules is not so simple. We must address various module definitions and different loading modes both not fully compatible. ECMAScript 6 specification proposes a standard solution to this problem offering native support for modules in a compact and effective way, quite a bit similar to the CommonJS module.
As per CommonJS, ES6 modules are stored in files. There is exactly one module per file and one file per module. We can export a functionality from a module using the export
keyword. The following code shows a module exporting a function myFunction()
, a class myClass
, and a constant myConst
using an approach called named export:
export function myFunction() {...}; export class myClass {...} export const myConst = 123;
If the previous module is stored in a file named myModule.js
, we can import one or more exported items using the import
keyword:
import {myClass, myFunction} from "myModule"; ...