Import and Export Modules in Node (JavaScript)

May 12, 2024

Declare variables

In this section, we'll define and initialize the variables for a user's first name and last name. We'll then export these variables from the module so they can be used in other parts of our application.

Here is how we structure our names.js file:

and here is the names files

1// Define the variables for first name and last name
2const firstName = "John";
3const lastName = "Smith";
4
5// Export the variables so they can be imported in other files
6module.exports = { firstName, lastName };
7

This code snippet demonstrates how to declare constants in JavaScript, which will hold the values of the user's first and last names. The module.exports statement makes these variables available for import in other JavaScript files, which is crucial for modular development where different parts of an application are kept in separate files.

Import Variables

Next, we'll use these variables in another file by importing them. This illustrates the modular nature of Node.js, allowing you to keep different parts of your application's logic separate and organized.

Here's how you can import and use the exported variables from names.js in app.js:

1// Import the fullName object from names.js
2const fullName = require('./names.js');
3
4// Output the imported fullName object to the console
5console.log(fullName);
6
7

This example shows how to require the module we previously exported. By requiring ./names.js, we import the object containing firstName and lastName. The console.log statement then prints this object to the console.

when you run

1node app.js
, you will see output like this:

1{ firstName: 'John', lastName: 'Smith' }
2

And, that's how you can import and export variables in Node.

Share this article