JavaScript ES6 Modules


Example

6

In ECMAScript 6, when using the module syntax (import/export), each file becomes its own module with a private namespace. Top-level functions and variables do not pollute the global namespace. To expose functions, classes, and variables for other modules to import, you can use the export keyword.

Note: Although this is the official method for creating JavaScript modules, it is not supported by any major browsers right now. However, ES6 Modules are supported by many transpilers.

export function greet(name) {
    console.log("Hello %s!", name);
}

var myMethod = function(param) {
    return "Here's what you said: " + param;
};

export {myMethod}

export class MyClass {
    test() {}
}

Using Modules

Importing modules is as simple as specifying their path:

import greet from "mymodule.js";

greet("Bob");

This imports only the myMethod method from our mymodule.js file.

It's also possible to import all methods from a module:

import * as myModule from "mymodule.js";

myModule.greet("Alice");

You can also import methods under a new name:

import { greet as A, myMethod as B } from "mymodule.js";

More information on ES6 Modules can be found in the Modules topic.