JavaScript _ Importing and Exporting Modules - GeeksforGeeks
JavaScript _ Importing and Exporting Modules - GeeksforGeeks
Importing a library: It means include a library in a program so that use the function is de ned in that library. For this, use ‘require’
function in which pass the library name with its relative path.
Example: Suppose a library is made in the same folder with le name library.js, then include the le by using require function:
which will return reference to that library. Now if there is area function de ned in the library, then use it as lib.area().
Exporting a library: There is a special object in JavaScript called module.exports. When some program include or import this module
(program), this object will be exposed. Therefore, all those functions that need to be exposed or need to be available so that it can
used in some other le, de ned in module.exports.
Expample : Write two different programs and then see how to use functions de ned in the library (Module) in given program. De ne
two simple functions in the library for calculating and printing area and perimeter of a rectangle when provided with length and
https://www.geeksforgeeks.org/javascript-importing-and-exporting-modules/ 5/10
7/13/2019 JavaScript | Importing and Exporting Modules - GeeksforGeeks
breadth. Then export the functions so that other programs can import them if needed and can use them.
<script>
// Area function
let area = function (length, breadth) {
let a = length * breadth;
console.log('Area of the rectangle is ' + a + ' square unit');
}
// Perimeter function
let perimeter = function (length, breadth) {
let p = 2 * (length + breadth);
console.log('Perimeter of the rectangle is ' + p + ' unit');
}
For importing any module, use a function called ‘Require’ which takes in the module name and if its user de ned module then its
relative path as argument and returns its reference.
Script.js
https://www.geeksforgeeks.org/javascript-importing-and-exporting-modules/ 6/10
7/13/2019 JavaScript | Importing and Exporting Modules - GeeksforGeeks
<script>
// Importing the module library containing
// area and perimeter functions.
// " ./ " is used if both the files are in the same folder.
const lib = require('./library');
Output:
Note: To run the script rst make both les in the same folder and then run script.js using NodeJs interpreter in terminal.
Recommended Posts:
ReactJS | Importing and Exporting
JavaScript | Modules
AngularJS | Modules
Dividing a Large le into Separate Modules in C/C++, Java and Python
https://www.geeksforgeeks.org/javascript-importing-and-exporting-modules/ 7/10