JavaScript modules split code into separate files that explicitly export and import dependencies. This modular architecture makes applications easier to develop and maintain.
In this article, we’ll cover the basics of using modules to untangle JavaScript codebases.
Why JavaScript Needed Modules
Before modules, JavaScript projects would include many scripts that implicitly shared global variables. This caused problems:
- Difficulty Managing Dependencies: No clarity on what code depends on what scripts.
- Namespace Collisions: Scripts could accidentally overwrite global variables.
- Hard to Reuse: No encapsulation of logic into components.
Modules solve these issues by allowing explicitly defined inter-module dependencies:
// module.js
export function add(a, b) {
return a + b;
}
// main.js
import {add} from './module.js';
add(1, 2); // 3
Much cleaner!
Using ES6 Export/Import
Modules leverage two new keywords:
- export: Makes variables and functions available to other modules