Language: EN

como-usar-modulos-nodejs

What are and how to use modules in Node.js

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

In summary, modules are a way to export code from a file so that 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 you will have them available to 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.

For example:

// 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;
}

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.

For example:

// 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

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

Exporting variables

We don’t have to exclusively export 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;

These will be consumed from our app in the same way we did with the functions.

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

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

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 that the results of the addition and subtraction operations are 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