What are modules in JavaScript and how do you use them?
What are modules in JavaScript and how do you use them?
98
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
import
andexport
keywords.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 ofthis
at the top level of a module isundefined
.CommonJS Modules
CommonJS is a module system used primarily in Node.js. It uses
require
to import modules andmodule.exports
to 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
import
andexport
, while CommonJS usesrequire
andmodule.exports
.Note
import
andexport
, supported in modern JavaScript environments.require
andmodule.exports
, primarily used in Node.js.type="module"
attribute in<script>
tags for ES6 modules.