In the previous segment, you learnt how to export functions from one module to another and how to import these functions using the require keyword. Now, you will learn different ways to export the constructs defined in one module to another.
In the last video, you looked at another way to export constructs from a module, which is an alternative to the traditional way. Here, you don't need to write an individual module.exports statement for each function that you need to import; you just need to use a single module.exports statement and define all the things to be exported inside it.
The code which you looked at in the previous video is given below:
circle Module:
const PI = 3.14; const calculateArea = r => PI * r * r; const calculateCircumference = r => 2 * PI * r; // using object literal notation to export everything at once module.exports = { calculateArea: calculateArea, calculateCircumference: calculateCircumference }
app Module:
const circle = require('./circle.js'); const area = circle.calculateArea(8); const circumference = circle.calculateCircumference(8); console.log(`Area = ${area}, Circumference = ${circumference}`);
Output:
Area = 200.96, Circumference = 50.24
In the next video, let's learn another method to export functions from a module.
The code which you looked at in the previous video is given below:
circle Module:
const PI = 3.14; // exporting functions while defining them module.exports.calculateArea = r => PI * r * r; module.exports.calculateCircumference = r => 2 * PI * r;
app Module:
const circle = require('./circle.js'); const area = circle.calculateArea(8); const circumference = circle.calculateCircumference(8); console.log(`Area = ${area}, Circumference = ${circumference}`);
Output:
Area = 200.96, Circumference = 50.24
This is another way to export constructs from one module to another.
Watch the next video to get a summary of all the three ways of exporting constructs from a module.
In this segment, you looked at two more ways of exporting something from a module, in addition to the traditional way.