What are modules in JavaScript and how do you use them?
What are modules in JavaScript and how do you use them?
472
18-Jun-2024
Updated on 19-Jun-2024
Ravi Vishwakarma
19-Jun-2024Modules in JavaScript are used to encapsulate code into reusable, disconnected pieces, making the code more maintainable, testable, and manageable. Modules allow you to export functions, objects, or values from one module so they can be imported and used in other modules.
This concept is essential for organizing large codebases and is supported by both the ES6 (ECMAScript 2015) module syntax and earlier module systems like CommonJS.
ES6 Modules
The ES6 module system, also known as ECMAScript modules (ESM), is the standard way to work with modules in modern JavaScript. It uses the
importandexportkeywords.Example: Creating and Using ES6 Modules
math.js (Module file)
main.js (Importing and using the module)
Key Features of ES6 Modules
this: The value ofthisat the top level of a module isundefined.CommonJS Modules
CommonJS is a module system used primarily in Node.js. It uses
requireto import modules andmodule.exportsto export them.Example: Creating and Using CommonJS Modules
math.js (Module file)
main.js (Importing and using the module)
Key Features of CommonJS Modules
Differences Between ES6 and CommonJS Modules
importandexport, while CommonJS usesrequireandmodule.exports.Note
importandexport, supported in modern JavaScript environments.requireandmodule.exports, primarily used in Node.js.type="module"attribute in<script>tags for ES6 modules.