1

I've been stuck on this issue for a while. I cannot describe it accurately enough to find solutions online - apologies if it is a duplicate question.

I want to access helloWorld() from module.js:

export function HelperProvider() {
  return class Helper {
    constructor() {
    }
    helloWorld() {
      console.log('Hello World');
    }
  }
}

In another file:

import { HelperProvider } from 'module.js'

const helperProvider = HelperProvider;
const helper = new helperProvider();

helper.helloWorld();

However, I encounter the following error:

Uncaught TypeError: helper.helloWorld is not a function

Any help would be very much appreciated.

2 Answers 2

1

You need to invoke the function HelperProvider to get the class.

const helperProvider = HelperProvider();

function HelperProvider() {
  return class Helper {
    constructor() {
    }
    helloWorld() {
      console.log('Hello World');
    }
  }
}

const helperProvider = HelperProvider();
const helper = new helperProvider();

helper.helloWorld();

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

2 Comments

Thank you @iota.
@kenwilde Happy to help.
0

You are using module features that's not out of the box in nodejs, if you want to use modules you'll need to set type: "module" in the package.json file... see details

If you wanna use node ways:

module.js

function HelperProvider() {
  return class Helper {

    constructor() {}

    helloWorld() {
      console.log("Hello World");
    }
  };
}

module.exports = HelperProvider;

index.js

const HelperProvider = require("./Helper");
const helperProvider = HelperProvider();
const helper = new helperProvider();

helper.helloWorld();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.