JavaScript Modules allow developers to break code into reusable and maintainable pieces. Modules encapsulate code and provide a way to share it between different files and parts of an application.
A module is a JavaScript file that exports code (e.g., variables, functions, classes) and can import code from other modules.
JavaScript introduced native module support in ES6 (ES2015). These are now widely supported by modern browsers and Node.js.
You can export code using export.
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
// greet.js export default function greet(name) { console.log(`Hello, ${name}!`); }
You can import code using import.
import { add, subtract } from './math.js'; console.log(add(5, 3)); // 8 console.log(subtract(5, 3)); // 2
import greet from './greet.js'; greet('Alice'); // Hello, Alice!
import { add as addition } from './math.js'; console.log(addition(5, 3)); // 8
import * as MathOperations from './math.js'; console.log(MathOperations.add(5, 3)); // 8 console.log(MathOperations.subtract(5, 3)); // 2
Dynamic imports allow modules to be loaded lazily, i.e., only when needed. This can improve performance.
import('./math.js').then((MathOperations) => { console.log(MathOperations.add(5, 3)); // 8 });
async function loadModule() { const MathOperations = await import('./math.js'); console.log(MathOperations.add(5, 3)); // 8 } loadModule();
Node.js traditionally uses the CommonJS module system. It uses require to import modules and module.exports to export them.
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
// greet.js export default function greet(name) { console.log(`Hello, ${name}!`); }
Feature | ES6 Modules | CommonJS |
---|---|---|
Syntax | import/export | require/module.exports |
Loading | Static | Dynamic |
Use Case | Modern JavaScript (Browsers, Node.js) | Primarily Node.js |
Default Export | Supported | Not explicitly supported |
When working with modules, bundlers like Webpack, Rollup, or Parcel can package your modules into a single file for deployment.
import { add, subtract } from './math.js'; console.log(add(5, 3)); // 8 console.log(subtract(5, 3)); // 2
import greet from './greet.js'; greet('Alice'); // Hello, Alice!
Group Related Code:
Avoid Circular Dependencies:
Lazy Load When Possible:
JavaScript Modules are essential for creating scalable, maintainable, and efficient applications.
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
The above is the detailed content of Understanding JavaScript Modules: Exporting and Importing Code Made Easy. For more information, please follow other related articles on the PHP Chinese website!