Reputation: 53
I've exported a function and imported it in Javascript, but the only way i can access the functions inside it is by typing it like this:
myModule.mainFunc().func1()
But what i'm trying to achieve is more like this:
myModule.mainFunc.func1()
Currently it gives an error if i try to reference to it like this.
I've tried returning the values of the functions as objects but it still needs me to call it as functions.
function greet() {
var hello = () => {
console.log("hello there");
};
var hi = () => {
console.log("hi there");
};
return { hello: hello, hi: hi }; // I've tried this doing it like this
}
export default {greet};
Here's how I'm importing it:
import greetings from "./index.js";
greetings.greet().hello()
Upvotes: 2
Views: 1566
Reputation: 27
Which environment you're running your code ? If it's NodeJS, make sure it supports ES6 Module as your current style of export and import. Normal NodeJS just supports CommonJS module.
Upvotes: 0
Reputation: 29282
You can't reference the functions defined inside greet
function as
myModule.mainFunc.func1()
because myModule.mainFunc
is a greet
function itself. What you want to import is the result of calling greet
function.
You can avoid invoking the greet
function manually by making your function an IIFE (Immediately Invoked Function Expression)
. Doing this will execute the function as soon as it is defined.
const greet = (function() {
var hello = () => {
console.log("hello there");
};
var hi = () => {
console.log("hi there");
};
return { hello, hi };
})();
export default { greet };
Now when you export greet
, you are not exporting greet
function, but the result of calling greet
function which is an object with two functions, hello
and hi
.
Upvotes: 2
Reputation: 79
define greet as an object
var greet = {
hello: () => {
console.log("hello there");
},
hi: () => {
console.log("hi there");
},
}
and access it like greet.hello()
Upvotes: 1