Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the difference between module.exports and exports in node

Shulou Source: shulou.com Published: 2022-06-02 06:36:12 10月04日 Update

This article mainly explains "what is the difference between module.exports and exports in node". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what's the difference between module.exports and exports in node?"

Exports is a reference to module.exports, similar to the following

Const exports = module.exports

How will the following results be derived?

Module.exports = 100

Exports = 3

It is obvious that 100 will be exported, after all, exports is redirected.

"how is it implemented in the node source code? The essence of "exports" can be seen from the source code.

Module wrapper

For more information, please see the source code: https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js#L1252, which is consistent with the conjecture.

As we all know, all the module code in node is wrapped in this function.

(function (exports, require, module, _ _ filename, _ _ dirname) {

Exports.a = 3

});

And the following source code indicates how exports was obtained.

Const dirname = path.dirname (filename)

Const require = makeRequireFunction (this, redirects)

Let result

/ / you can see the essence of exports from here.

Const exports = this.exports

Const thisValue = exports

Const module = this

If (requireDepth = 0) statCache = new Map ()

If (inspectorWrapper) {

Result = inspectorWrapper (compiledWrapper, thisValue, exports

Require, module, filename, dirname)

} else {

/ / here is the module wrapper function

Result = compiledWrapper.call (thisValue, exports, require, module

Filename, dirname)

} at this point, I believe you have a deeper understanding of "what is the difference between module.exports and exports in node". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Source code content function substance module learning practical deeper well known code interest practicality practical pointing easy to operate method more friends results website Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Docker Huawei Shulou Information Shulou Tech Info