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.

kenwilde
  • 121
  • 8

2 Answers2

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();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
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();
Leandro William
  • 457
  • 5
  • 12