SenKi
SenKi

Reputation: 53

how to export javascript function as a module

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

Answers (3)

Thang Le
Thang Le

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

Yousaf
Yousaf

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

Nick Olay
Nick Olay

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

Related Questions