exports 是一个存在于 module.exports 上的变量.它基本上是您在需要文件时导出的内容.//foo.jsmodule.exports = 42;//main.jsconsole.log(require("foo") === 42);//真的exports 本身存在一个小问题._global 范围 context+ 和 module 不 相同.(在浏览器中,全局范围上下文和 window 是相同的).//foo.jsvar 出口 = {};//创建一个名为exports的新局部变量,并与//生活在 module.exports 上出口 = {};//和上面一样module.exports = {};//只是有效,因为它是正确的"导出//bar.js出口.foo = 42;//这不会创建一个新的导出变量,所以它只是工作阅读关于出口的更多信息Looking at a random source file of the express framework for NodeJS, there are two lines of the code that I do not understand (these lines of code are typical of almost all NodeJS files)./** * Expose `Router` constructor. */exports = module.exports = Router;and/** * Expose HTTP methods. */var methods = exports.methods = require('./methods');I understand that the first piece of code allows the rest of the functions in the file to be exposed to the NodeJS app, but I don't understand exactly how it works, or what the code in the line means. I believe the 2nd piece of code allows the functions in the file to access methods, but again, how exactly does it do this.Basically, what are these magic words: module and exports? 解决方案 To be more specific:module is the global scope variable inside a file.So if you call require("foo") then :// foo.jsconsole.log(this === module); // trueIt acts in the same way that window acts in the browser.There is also another global object called global which you can write and read from in any file you want, but that involves mutating global scope and this is EVILexports is a variable that lives on module.exports. It's basically what you export when a file is required.// foo.jsmodule.exports = 42;// main.jsconsole.log(require("foo") === 42); // trueThere is a minor problem with exports on it's own. The _global scope context+ and module are not the same. (In the browser the global scope context and window are the same).// foo.jsvar exports = {}; // creates a new local variable called exports, and conflicts with// living on module.exportsexports = {}; // does the same as abovemodule.exports = {}; // just works because its the "correct" exports// bar.jsexports.foo = 42; // this does not create a new exports variable so it just worksRead more about exports 这篇关于“module.exports"做什么?和“exports.methods"在 NodeJS/Express 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!