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.
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');
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.
const functions = require('./modules');let { myLogger, myNumbers } = functionsconsole.log("Calling myLogger function:")myLogger();console.log("\n Printing myNumbers list:")console.log(myNumbers);