como-usar-modulos-nodejs

What are and how to use modules in Node.js

  • 2 min

ESM (ECMAScript Modules) are a modern way to organize and reuse code in JavaScript.

In short, modules are a way to export the code from one file so it can be used by other files.

We can define a series of functions, variables, or constants in a file and export them. Then, another file can import them and have them available for use.

This allows us to create libraries and organize and reuse our code in a structured way.

Using Modules in Node.js

Creating a Module

Let’s see how to create a module. Simply create a JavaScript file. For example, operaciones.mjs. In this file, create the functions or methods you want to export.

// Function to add two numbers
export function sumar(a, b) {
 return a + b;
}

// Function to subtract two numbers
export function restar(a, b) {
 return a - b;
}
Copied!

In this code, we define two functions, sumar() and restar(), and export them using the export keyword.

Importing the Module

Once we have created our module with functions or methods, we can import it into another JavaScript file to use those functions or methods.

Create a new JavaScript file where you want to import the functions or methods from the module. For example, app.js.

In the app.js file, import the functions or methods from the module using the import keyword.

// Import the functions from the operaciones.mjs module
import { sumar, restar } from './operaciones.mjs';

// Use the imported functions
console.log(sumar(5, 3)); // Output: 8
console.log(restar(10, 4)); // Output: 6
Copied!

In this code, we import the functions sumar() and restar() from the operaciones.mjs module using the destructuring syntax {}.

Exporting Variables

We don’t have to export only functions; we can also export variables and even constants. For example, like this.

// Export a variable
export let nombre = 'Luis';

// Export a constant
export const PI = 3.14159265359;
Copied!

They would be consumed from our app in the same way we did with functions.

import { nombre, PI } from './variables.mjs';

console.log(nombre); // Output: Luis
console.log(PI); // Output: 3.14159265359
Copied!

Running the Program

Now, to run the program and see the results, simply use Node.js to execute the app.js file:

node app.js

You will see the result of the addition and subtraction operations printed in the console, using the functions imported from the operaciones.mjs module.

Download the Code

All the code from this post is available for download on Github. github-full