简体   繁体   English

如何创建一个JavaScript对象以通过export.module导出?

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

I have an javascript test class 我有一个JavaScript测试课程

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. 我期望有一个Test的测试实例,以便test.url将返回null。 How would I change the source so that var test = new Test() works without throwing an error? 我将如何更改源,以便var test = new Test()正常工作而不会引发错误?

You'll want to use module.exports instead of exports.module 你会想用module.exports代替exports.module

The way you have it written currently, you'd be able to reference your Test object like so 当前编写方式,您可以像这样引用Test对象

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

You are doing 你在做
exports.module = Test;
So what gets exported from test is module hence, you will have to 因此,从test导出的是module因此,您必须

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 如果您直接想要使用Test类,则可以在test.js文件中使用module.exports = Test

and then you can directly do 然后你可以直接做
var Test = require('./test'); var test = new Test();
where you are importing it. 您将其导入的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM