Basics
Node.js Modules
Using Node.js Modules
Node.js modules use require and ES modules with import/export.
Introduction to Node.js Modules
Modules are a fundamental aspect of Node.js, allowing developers to organize code into manageable, reusable files. In Node.js, you can use CommonJS modules with require or ES6 modules with import/export syntax. This flexibility helps developers to structure their applications efficiently.
CommonJS Modules with require
CommonJS is the original module system used in Node.js. Modules are loaded synchronously, and the syntax for using them is straightforward:
In the example above, math.js
exports a function using module.exports
. This function is then imported into app.js
using require('./math')
.
ES6 Modules with import/export
ES6 modules are the standardized module system in JavaScript, allowing for more flexible and readable syntax. Modules are loaded asynchronously, and the syntax is as follows:
In this example, the add
function is exported using the export
keyword in math.js
. It is then imported in app.js
using the import
keyword.
Choosing Between CommonJS and ES6 Modules
While CommonJS is widely used in Node.js, ES6 modules offer a more modern and flexible approach, especially useful in environments that support it natively, such as modern browsers. However, in Node.js, CommonJS is still prevalent due to legacy code and existing libraries.
To use ES6 modules in Node.js, ensure your project file has an "type": "module"
field in package.json
, or use the .mjs
extension for your module files.
Summary
Node.js modules are a powerful feature that facilitates code organization and reuse. Whether you choose CommonJS or ES6 modules, understanding their differences and use cases is crucial for modern JavaScript development. Use require
for compatibility with older Node.js projects and libraries, or import/export
for a modern, ES6-compliant codebase.
Basics
- Previous
- Security Basics
- Next
- Global Objects