Reputation: 13
I have the following IIFE in a file iife.js
:
(function() {
return "Hello World!";
}());
I would like to get the result of this function in another file:
var result = require("./iife");
console.log(result);
But the result
is {}
instead of Hello World!
.
How can I access the return value of the IIFE from another file, preferably without changing the code in iife.js
?
Upvotes: 1
Views: 709
Reputation: 944075
You have to capture it on the left hand side:
const return_value = (function() {
return "Hello World!";
}());
But if you want to export it from a CommonJS module then you need to assign it to the module's exports:
module.exports = return_value;
But if you are using a CommonJS module then there is no point in using an IIFE in the first place. IIFEs are used to isolate variables, which modules do anyway.
module.exports = "Hello World!";
Upvotes: 8