Modules and Namespaces in JavaScript
Key Concepts
- Modules
- Namespaces
- Exporting and Importing Modules
- Module Bundlers
- CommonJS vs ES6 Modules
Modules
Modules in JavaScript are self-contained units of code that can be reused across different parts of an application. They help in organizing code into manageable and maintainable pieces. Each module has its own scope, preventing variable name conflicts and allowing for better encapsulation.
Example:
// math.js export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; }
Namespaces
Namespaces are used to group related functionality under a single name to avoid naming collisions. They provide a way to organize code and make it easier to manage large codebases. Namespaces can be thought of as containers for variables, functions, and classes.
Example:
let MyNamespace = { add: function(a, b) { return a + b; }, subtract: function(a, b) { return a - b; } }; console.log(MyNamespace.add(5, 3)); // Outputs: 8
Exporting and Importing Modules
Exporting and importing modules allow you to share code between different files. The export
keyword is used to make functions, objects, or primitive values available to other modules, while the import
keyword is used to bring in functionality from other modules.
Example:
// main.js import { add, subtract } from './math.js'; console.log(add(5, 3)); // Outputs: 8 console.log(subtract(5, 3)); // Outputs: 2
Module Bundlers
Module bundlers are tools that combine multiple JavaScript files into a single file, which can then be included in a web page. Popular module bundlers include Webpack, Rollup, and Parcel. They help in optimizing the loading time of web applications by reducing the number of HTTP requests.
Example:
// webpack.config.js module.exports = { entry: './main.js', output: { filename: 'bundle.js' } };
CommonJS vs ES6 Modules
CommonJS is a module system used primarily in Node.js, where modules are loaded synchronously using the require
function. ES6 (ECMAScript 2015) introduced a new module system for the browser, using the import
and export
keywords. ES6 modules are loaded asynchronously and are the standard for modern JavaScript applications.
Example:
// CommonJS const math = require('./math.js'); console.log(math.add(5, 3)); // Outputs: 8 // ES6 Modules import { add } from './math.js'; console.log(add(5, 3)); // Outputs: 8