2

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()

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

define greet as an object

var greet = {
    hello: () => {
        console.log("hello there");
    },
    hi: () => {
        console.log("hi there");
    },
}

and access it like greet.hello()

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.