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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
The Nomad
  • 7,155
  • 14
  • 65
  • 100
  • how do you export in `mod1.js`? – Sagiv b.g Feb 03 '18 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');` – briosheje Feb 03 '18 at 10:49
  • Possible duplicate of [how to get a variable from a file to another file in node.js](https://stackoverflow.com/q/7612011/218196) – Felix Kling Feb 04 '18 at 06:06

1 Answers1

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.

Himanshu Mittal
  • 584
  • 1
  • 6
  • 21