Web design · Development · SEO
ES Modules
ES modules explained: organizing JavaScript | scinet
Editorially reviewed ·
Clear definition
ES modules are JavaScript’s standardized module system. One file can explicitly export functions or values; another imports that interface. ES stands for ECMAScript, the language standard behind JavaScript.
Imagine a website with navigation, a form and an appointment display. You do not want to find every function in one large file. Modules help separate responsibilities and make dependencies visible. The module system does not choose a sensible structure for you, though.
What import and export connect
A date-formatting function can live in its own file. export specifies that other modules may use it. The importing file identifies the exported name and module path. Local helper values do not have to become global variables.
Named exports and a default export use different syntax. The import must match the exported interface. Replacing only a library filename during an update can therefore still cause an error. Check which names the new module actually exposes.
At a glance
How a module starts in the browser
A browser entry point can be a script element with type="module" and a path to the starting file. Further dependencies are loaded from there. Relative imports such as ./format.js are resolved against the importing file. A bare package name requires a resolution mechanism in the browser, such as an import map or a build.
Test through a local web server. Opening files directly through file:// can run into security restrictions. The server must also deliver suitable JavaScript content types and, for cross-origin resources, the required CORS permissions.
What modules can improve in maintenance
I would divide files by clear responsibilities: a date-formatting function, for example, and another piece of code for opening navigation. A formatting change should not accidentally affect the menu. Small, explicit interfaces make those boundaries easier to inspect.
Modules do not automatically guarantee smaller downloads. A build can remove unused code under suitable conditions, but the actual output still needs checking. Numerous small network requests also depend on the delivery setup. Decide from the project whether native modules are sufficient or build tools would help.
Related reading: JavaScript · Bootstrap · Bootstrap 6 Alpha compared.
Practical code example
Exporting and importing a function
Original example with two separate files in the same folder. Include app.js using <script type="module" src="./app.js"></script>.
// format.js
export function formatDate(value) {
return new Intl.DateTimeFormat("en-GB").format(value);
}
// app.js (separate file)
import { formatDate } from "./format.js";
console.log(formatDate(new Date()));
Sources and further reading
- Documentation JavaScript modules MDN Web Docs · Checked
- Documentation import MDN Web Docs · Checked
- Documentation export MDN Web Docs · Checked