module.exports
module.exports is an empty object and a property on the module object. Module is a special object in NodeJS which contains information about the current module. The exports property is used to expose properties or functions of the current module. Use require to import properties from some module.
// file.js module.exports = “Hello world”;
|
// file2.js module.exports = { fn: function () { // ... } }; |
// app.js var message = require(‘./file’); console.log(message); // Hello world var file2 = require(‘./file2’); console.log(file2.fn()); // call fn on the file2 |
With the introduction of ES Modules via ES6, an export and import keyword can be used for exporting and importing properties.
// file.js const message = “Hello world”; export default message; |
// file2.js export function fn() { // ... } |
// app.js import message from ‘./file’; console.log(message); // Hello world import { fn } from ‘./file2’; console.log(fn()); // call fn on the file2 |
“module.exports” Tech Bite was brought to you by Kenan Klisura, Lead Software Engineer at Atlantbh.
Tech Bites are tips, tricks, snippets or explanations about various programming technologies and paradigms, which can help engineers with their everyday job.