xxxxxxxxxx
require function returns exports of the require module.
module.exports is the returned object.
1)use module.exports to export single varibale e.g one class or one function
e.g module.exports= Calculator.
2)use exports to export multiple named variables
export.add = (a,b)=> a+b;
export.multiple=(a,b)=> a*b;
xxxxxxxxxx
function foo(x, y) {
return x + y;
}
function bar(x, y) {
return x - y;
}
//You can also export numbers, classes, objects, etc
const foobar = 33;
module.exports = { foo, bar, num };
xxxxxxxxxx
var users = [
{ userName: "BarneyRubble", age: 38 },
{ userName: "WilmaFlintstone", age: 37 },
{ userName: "FredFlintstone", age: 36 }
];
module.exports.getAllUsers = function(){
return users;
}
xxxxxxxxxx
module.exports = {
method: function() {},
otherMethod: function() {},
};
const myModule = require('./myModule.js');
const method = myModule.method;
const otherMethod = myModule.otherMethod;
// OR:
const {method, otherMethod} = require('./myModule.js');
xxxxxxxxxx
mycoolmodule/index.js
module.exports = "123";
routes/index.js
var mymodule = require('mycoolmodule')
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
console.log(mymodule);
});
/*will show 123 in the terminal*/
module.exports = router;
xxxxxxxxxx
//2 ways of module.exports
// 1
function celsiusToFahrenheit(celsius) {
return celsius * (9/5) + 32;
}
module.exports.celsiusToFahrenheit = celsiusToFahrenheit;
//2
module.exports.fahrenheitToCelsius = function(fahrenheit) {
return (fahrenheit - 32) * (5/9);
};
xxxxxxxxxx
// First Export from other file
export default exampleFunction;
// for multiple exports use:
module.exports = { exampleFunction1, exampleFunction2 };
// Then we import in the file where we want to use our functions
import exampleFunction from "./otherFile.js";
// for multiple imports, we desctructure
import { exampleFunction1, exampleFunction2 } from "./otherFile.js"
// Check MDN for more info on JS exports.
// NOTE: if running on node, add "type": "module" to your package.json file
//
xxxxxxxxxx
// foo.js
module.exports = 42;
// main.js
console.log(require("foo") === 42); // true
xxxxxxxxxx
let value = "string bir ifade"
let number = 54;
module.exports = value /!bu şekildede oluyor
module.exports = value