As your application grows, keeping all code in a single file becomes unmanageable. Modules allow you to break up your code into separate files. This makes it easier to maintain the code-base, reuse logic, and keep the global namespace clean.
ES6 Modules (also known as ECMAScript Modules or ESM) are the official standard format to package JavaScript code for reuse.
You can export multiple values (functions, variables, classes) from a module using named exports. You must use the exact same name when importing them.
// file: math.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
// file: user.js
const name = "Ragini";
const age = 25;
export { name, age };
You can have only one default export per file. This is useful for modules that export a single class or a main function. You can name it whatever you want when importing.
// file: message.js
const message = () => {
const name = "Jesse";
const age = 40;
return name + ' is ' + age + ' years old.';
};
export default message;
You import modules into a file using the import keyword.
Named exports must be destructured using curly braces {}.
import { PI, add } from "./math.js";
console.log(PI);
console.log(add(5, 10));
Default exports do not use curly braces.
import message from "./message.js";
console.log(message());
You can import all exported values as an object.
import * as MathUtils from "./math.js";
console.log(MathUtils.PI);
console.log(MathUtils.add(2, 3));
| Feature | Modules | Non-Modules (Scripts) |
|---|---|---|
| Scope | File Scoped (Variables are private by default) | Global Scoped (Variables can pollute window) |
| Strict Mode | Always enabled ("use strict") |
Optional |
| Loading | Deferred by default (doesn't block HTML) | Blocks HTML parsing unless defer is used |
| Execution | Executed only once | Executed every time included |
file://), modules will be blocked by CORS policy.
Test your understanding of JavaScript Modules.
apiKey with the value "12345ABC".calculateTax in a file called tax.js.utils.js that exports multiple functions (add, subtract, multiply).mathOps.api.js exports a function named fetchData.getUserData to avoid naming conflicts.module.js exports a default function init and a named constant version.module.js.main.js.