0

index.js of imported npm module myLib

const Mod1 = require('./mod1');
const Mod2 = require('./mod2');
const Mod3 = require('./mod3');

module.exports = {
  Mod1,
  Mod2,
  Mod3,
};

mod1.js

class Mod1 {
  constructor(url) {
  }
}

file using the above npm module

const Mod1 = require('myLib');
const instance = new Mod1();

This is throwing the following error when trying to run it:

const instance = new Mod1();
                ^
TypeError: Mod1 is not a constructor

How should I reference the class from a single import index.js so that I may be able to create an instance of the class?

3
  • how do you export in mod1.js? Commented Feb 3, 2018 at 10:42
  • the require statement should properly include Mod1, otherwise you should use export default Mod1;. To properly import your module, use: const { Mod1 } = require('path_to_mylib'); Commented Feb 3, 2018 at 10:49
  • Possible duplicate of how to get a variable from a file to another file in node.js Commented Feb 4, 2018 at 6:06

1 Answer 1

1

There seems to be a slight mistake in your import, the actual import will be like:

const {Mod1} = require('myLib');

which will pull the class from the file and give it to you (ES6 feature)

you can also do it like:

const Mod1 = require('myLib').Mod1;

hope this helps.

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

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.