Keith John Hutchison
Keith John Hutchison

Reputation: 5277

How do you create a javascript object to export via export.module?

I have an javascript test class

var Test = function() {
    var _object = {} ;
    _object.url = null ;
    return _object ;
}
exports.module = Test ;

Which I can then import via

var Test = require('./test') ;

When I do this however I get an error.

var test = new Test() ;
TypeError: Test is not a constructor

I'm expecting to have a test instance of Test such that test.url will return null. How would I change the source so that var test = new Test() works without throwing an error?

Upvotes: 0

Views: 45

Answers (2)

Hannan
Hannan

Reputation: 514

You are doing
exports.module = Test;
So what gets exported from test is module hence, you will have to

var test = require('./test'); var Test = new test.module();


If you directly want to use your Test class then you can module.exports = Test in your test.js file

and then you can directly do
var Test = require('./test'); var test = new Test();
where you are importing it.

Upvotes: 1

Charlie L
Charlie L

Reputation: 463

You'll want to use module.exports instead of exports.module

The way you have it written currently, you'd be able to reference your Test object like so

var Test = require('./test');
var test = new Test.module();

Upvotes: 2

Related Questions