Why do we use export in nodejs?

I am new to Nodejs. For me module.exports, exportsboth are an empty object. module.exportscan expose a function, but exportscannot do it. Everything can be achieved using module.exports.

So why do we use exports, even if we have module.exports? What are the advantages exportsover module.exports?

+4
source share
4 answers

TL DR

You can use:

exports.x = 1;
exports.y = 2;
exports.z = 3;

as a shorter way to write:

module.exports.x = 1;
module.exports.y = 2;
module.exports.z = 3;

The only advantage is not to print.

But you should write:

module.exports = {
    x: 1,
    y: 2,
    z: 3
};

as this will not work:

exports = {
    x: 1,
    y: 2,
    z: 3
};

because it will not change module.exportsand it module.exports, which is actually exported .

Description

, , . exports, , module, exports :

module.exports === exports

:

exports.x = 10;

( , ), . x exports.x, module.exports.x.

:

exports = {x: 10};

exports, module.exports () . , exports.x, module.exports.x, :

module.exports !== exports

, , exports, module.exports:

module.exports = {x: 10};

module.exports exports :

module.exports !== exports

module.exports, , .

module.exports exports:

module.exports = {x: 10};
exports = module.exports;

:

exports = {x: 10};
module.exports = exports;

:

exports.y = 20;

.

(), (). , :

function private1() {
    // ...
}
function private2() {
    // ...
}
function public1() {
    // ...
}
function public2() {
    // ...
}

:

module.exports.public1 = public1;
module.exports.public2 = public2;

exports.public1 = public1;
exports.public2 = public2;

module.exports = {
    public1: public1,
    public2: public2
};

module.exports = {
    public1,
    public2
};

exports = {
    public1: public1,
    public2: public2
};

exports = {
    public1,
    public2
};

, exports , module.exports , , , , . module.exports .

.

. :

+6

- JavaScript export. export - JavaScript, , , module.exports. node.js "" module.exports require. JS Node :

// your code
var module = { exports: {} };
var exports = module.exports;

return module.exports;

, export.a = 9;, module.exports.a, JavaScript, , , - ; module.exports - . - , module.exports, export module.exports .

+2

. exports.myFunc = function(){}; module.exports.myFunc = function(){};

0

module.exports node, .

with indepdendent, exportsyou can only export methods that you want to make available to other modules. It is like performing certain functions as publicwell private.

0
source

Source: https://habr.com/ru/post/1664541/


All Articles