在此页面(http://docs.nodejitsu.com/articles/getting-started/what-is-require)上,它声明"如果要将导出对象设置为函数或新对象,则必须使用module.exports对象."
我的问题是为什么.
// right
module.exports = function () {
console.log("hello world")
}
// wrong
exports = function () {
console.log("hello world")
}
Run Code Online (Sandbox Code Playgroud)
我console.log结果(result=require(example.js)),第一个是[Function]第二个{}.
你能解释一下背后的原因吗?我在这里阅读帖子:在Node.js中的module.exports vs exports.它很有帮助,但没有解释它以这种方式设计的原因.如果直接退回出口参考会有问题吗?
我正在尝试从Node.js 6.2.0中的CommonJS模块导出ES6类
class MyClass{
//class contents here
}
exports = MyClass;
Run Code Online (Sandbox Code Playgroud)
然后在另一个模块中导入它:
var MyClass = require('/path/to/module.js')
var instance = new MyClass();
Run Code Online (Sandbox Code Playgroud)
但是我得到以下异常:
TypeError: MyClass is not a constructor
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
请注意,我没有使用Babel/Tranceur,它是纯粹的JS,在最新的Node 6.2.0中实现,根据Kangax,93%实现了ES6.
//编辑:这对export和module.exports来说不是问题.虽然单独使用导出,但我得到了一些__proto__set的对象.