Basics
Node.js Modules
Using Node.js Modules
Node.js modules use require and ES modules with import/export.
Introduction to Node.js Modules
Node.js modules are integral to building applications in Node.js. They allow developers to structure code in reusable and maintainable chunks. Node.js supports two types of modules: CommonJS modules (using require
) and ES Modules (using import/export
).
CommonJS Modules: Using Require
CommonJS is the module format used in Node.js by default. Modules are loaded synchronously using the require
function. Each module in Node.js is encapsulated in its own scope, meaning variables and functions declared in one module are not available to other modules unless explicitly exported.
Here's a basic example of how to create and use a CommonJS module:
In the example above, we define a simple function add
and export it using module.exports
. This makes the add
function available to any file that requires math.js
.
Now, let's import and use this module in another file:
ES Modules: Using Import/Export
ES Modules are a standardized module system in JavaScript. They are now fully supported in Node.js from version 12 onwards, but you need to use the .mjs
extension or set "type": "module"
in your package.json
to use them.
Here's how you can create and use an ES Module:
In the math.mjs
file above, we use the export
keyword to make the add
function accessible to other modules. Now, let's import and use this ES Module in another file:
Choosing Between CommonJS and ES Modules
The choice between CommonJS and ES Modules will depend on your project's requirements and compatibility. CommonJS is easier to use in older Node.js applications, while ES Modules offer a more modern and flexible syntax that aligns with the latest JavaScript standards. Consider using ES Modules for newer projects where possible.
Conclusion
Understanding modules in Node.js is essential for effective application development. Whether you choose CommonJS or ES Modules, organizing your code into manageable pieces will enhance maintainability and scalability. As Node.js evolves, ES Modules are expected to become the dominant module system, so familiarity with both is advantageous.
Basics
- Previous
- Security Basics
- Next
- Global Objects