0

I'm trying to make some discord bots, and I'm getting frustrated trying to use a class I created in another script. The script in question looks like this:

// utils.js

class BotUtils {
   constructor(param1, param2, ...) {
      this.param1 = param1;
      this.param2 = param2;
      ...
      }

    someMethod() {
    doSomething;
    }
}

module.exports = {BotUtils};

In my bot script, I have:

// bot.js
const botUtils = require('./BotUtils');

let utils = new BotUtils(param1, param2, ...);

And I get TypeError: BotUtils is not a constructor

I've also tried using new but it doesn't work. I need to construct the class with the specific parameters. What's the correct way to do this?

1 Answer 1

2

You are exporting an object with the class BotUtils as a property from your module. To create an instance of the class, you need to reference the property i.e.

let utils = new botUtils.BotUtils(param1, param2, ...);

If you want to export only the BotUtils class then you can do so by removing the brackets

module.exports = BotUtils;

Then when you require the module the class is what is returned, this is closer to your original code but with a small tweak

const BotUtils = require('./utils');

Additionally, if you are using ES modules, this gets a lot easier with named exports

import { BotUtils } from './utils'
Sign up to request clarification or add additional context in comments.

3 Comments

Christ, I've been bashing my head against the desk for hours trying to fix this and it's that simple. Thanks!
Also I tried using ES modules but that was a whole other headache so I went back to the normal exports. Works now though.
@dbm that's a whole other can of worms. It was on the off chance you were using ES6 already.

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.