Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

module
exports
javascript

What are module exports in JavaScript?

Educative Answers Team

The export statement is used in Javascript modules to export functions, objects, or primitive values from one module so that they can be used in other programs (using the ‘import’ statement).

A module encapsulates related code into a single unit of code. All functions related to a single module are contained in a file.

Module exports are the instructions that tell Node.js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.

svg viewer

Syntax

The following code exposes a function to be exported in the file Log.js.

module.exports = function (msg) { 
    console.log(msg);
};

We can now use the above module as shown below.

var msg = require('./Log.js');

msg('Hello World');

Code

The following code declares and exports a list (myNumbers) and a function (myLogger()) in the file modules.js. We then import these modules into our main file (index.js), which allows us to call these functions there.

index.js
modules.js
const functions = require('./modules');
let { myLogger, myNumbers } = functions

console.log("Calling myLogger function:")
myLogger();
console.log("\n Printing myNumbers list:")
console.log(myNumbers);

RELATED TAGS

module
exports
javascript
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring