ES中的export和modules.export有什么区别

有时我看到:导出默认类…

module.exports = …

有什么区别? 我们将在哪种情况下使用哪一个?

只是为了澄清。 这是特定于node.js

在节点中创build一个模块就好像你正在用下面的函数包装它。 实际上,这或多或less是节点正在做的事情。

function (exports, require, module, __filename, __dirname) { } 

所以,exportsvariables实际上是对module.exports的引用,像这样,可以有两个variables指向同一个对象。 导出和module.exports引用内存中的同一个点。 您必须小心使用导出,因为有一些与JavaScript对象相关的“黑暗”部分,并且有一些模式可能会被破坏。 这里是一个例子:

dependency_exports.js

 exports = function () { console.log('dependency'); } // Place console.log to see the contents of the exports and module.exports console.log(exports); console.log(module.exports); 

app.js

 var dependency = require('./dependency_exports'); dependency(); 

为什么dependency_exports.js文件中的两个console.log文件在打印不同的对象时,如果指向相同的内存呢? 请记住,它是对module.exports的引用。 当我们为该variables(出口)分配另一个值时,我们会中断参考,并创build一个新的内存点。 它不会更新module.exports中的引用。

所以现在如果我们尝试做这样的事情:

 dependency(); 

由于这个问题,我们会看到一个错误回来。