How to construct new class using ES6 syntax from library module?

时间:2018-02-03 10:04:31

标签: javascript node.js ecmascript-6

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?

1 个答案:

答案 0 :(得分: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.