You are on page 1of 1

Modules

One of the most error-prone and confusing aspects of JavaScript has long been the “shared
everything” approach to loading code. Whereas other languages have concepts such as
packages, JavaScript lagged behind, and everything defined in every file shared the same global
scope. As web applications became more complex and the amount of JavaScript used grew, the
“shared everything”
approach began to show problems with naming collisions, security concerns, and more. One of the
goals of ECMAScript 6 was to solve this problem and bring some order into JavaScript
applications. That’s where modules come in.
What are Modules?
Modules are JavaScript files that are loaded in a special mode (as opposed to scripts, which are
loaded in the original way JavaScript worked). At the time of my writing, neither browsers nor
Node.js have a way to natively load ECMAScript 6 modules, but both have indicated that there will
need to be some sort of opt-in to do so. The reason this opt-in is necessary is because module
files have very
different semantics than non-module files:
1. Module code automatically runs in strict mode and there’s no way to opt-out of strict mode.
2. Variables created in the top level of a module are not automatically added to the shared global
scope. They exist only within the top-level scope of the module.
3. The value of this in the top level of a module is undefined.
4. Modules do not allow HTML-style comments within the code (a leftover feature from the early
browser days).
5. Modules must export anything that should be available to code outside of the module.
These differences may seem small at first glance, however, they represent a significant change in
how JavaScript code is loaded and evaluated.
Module JavaScript files are created just like any other JavaScript file: in a text editor and typically
with the .js extension. The only difference during development is that you use some different
syntax.
Basic Exporting and Importing
The export keyword is used to expose parts of published code to other modules. In the simplest
case, you can place export in front of any variable, function, or class declaration to export it from the
module. For example:
// export data
export var color = "red";
export let name = "Nicholas";
export const magicNumber = 7;
// export function
export function sum(num1, num2) {
return num1 + num1;
}
// export class
export class Rectangle {
constructor(length, width) {
this.length = length;
this.width = width;
}
}
// this function is private to the module
function subtract(num1, num2) {
return num1 - num2;
}
// define a function
function multiply(num1, num2) {
return num1 * num2;
}
// export later
export multiply;

You might also like