Advanced
Modules and Imports
Modules and Imports in JavaScript Modules allow JavaScript code to be divided into smaller, reusable files. This improves code maintainability and organization.
Exporting in CommonJS
Create a file called math.js
:
Importing in CommonJS
In app.js
, import the module using require()
:
Exporting a Single Value
Importing a single exported function:
ES6 Modules (ESM)
ES6 Modules are the modern way to work with modules in JavaScript. They use export
and import
and work in both browsers and Node.js (with "type": "module"
in package.json
).
Named Exports
Create math.js
:
Default Exports
Only one default export per file:
Importing in ES6 Modules
Importing Named Exports
In app.js
:
Importing a Default Export
Importing Everything from a Module
Using ES6 Modules in Node.js
To use ES6 modules in Node.js, add "type": "module"
in package.json
:
Then, use import
instead of require()
.
Differences Between CommonJS and ES6 Modules
FeatureCommonJS (require
)ES6 Modules (import
)Default inNode.jsModern JavaScript (ES6)Syntaxrequire()
/ module.exportsimport
/ export
Load TypeSynchronousAsynchronousCan be used in BrowsersNo (without bundlers)Yes (Supported in modern browsers)
When to Use Which?
Use CommonJS for Node.js applications that do not require modern JavaScript syntax.
Use ES6 Modules for modern JavaScript projects, browsers, and future-proof development.
Conclusion
Modules improve code reusability and organization. ES6 Modules (import/export
) are the standard for modern JavaScript, while CommonJS (require/module.exports
) is still widely used in Node.js. The next section will cover working with databases in JavaScript, focusing on connecting Node.js to relational and NoSQL databases.
Join our Community Forum
Any other questions? Get in touch