Defining a module

suggest change

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.

// not exported
function somethingPrivate() {
    console.log('TOP SECRET')
}

export const PI = 3.14;

export function doSomething() {
    console.log('Hello from a module!')
}

function doSomethingElse(){ 
    console.log("Something else")
}

export {doSomethingElse}

export class MyClass {
    test() {}
}

Note: ES5 JavaScript files loaded via <script> tags will remain the same when not using import/export.

Only the values which are explicitly exported will be available outside of the module. Everything else can be considered private or inaccessible.

Importing this module would yield (assuming the previous code block is in my-module.js):

import * as myModule from './my-module.js';

myModule.PI;                 // 3.14
myModule.doSomething();      // 'Hello from a module!'
myModule.doSomethingElse();  // 'Something else'
new myModule.MyClass();      // an instance of MyClass
myModule.somethingPrivate(); // This would fail since somethingPrivate was not exported

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Modules:
* Syntax
* Defining a module

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde