Node.js — module.exports vs exports, what’s the difference ?

Simple use of exports,

// --  hello.js
exports.anything = function() {
  console.log('I am anything.');
};
// -- hello-runner.js
const hello = require('./hello');

// let's see what's there in hello variable
console.log(hello); // {anything: Function}

hello.anything(); // I am anything.

Similar use of module.exports

// --  hello.js
module.exports.anything = function() {
  console.log('I am anything.');
};
// -- hello-runner.js
const hello = require('./hello');

// let's see what's there in hello variable
console.log(hello); // {anything: Function}

hello.anything(); // I am anything.

Similar output.

So, what the difference ? thinking

Exports is just module.exports's little helper. Your module returns module.exports to the caller ultimately, not exports. All exports does is collect properties and attach them to module.exports

BUT...

IF module.exports doesn't have something on it already. If there's something attached to module.exports already, everything on exports is ignored.

// -- hello.js
module.exports = {
  hi: function() {
    console.log('hi');
  },
};

// ALERT - this won't be exported.
exports.bye = function() {
  console.log('bye');
};

What if we assign a value to module.exports or exports ?

// hello.js file
module.exports = {a: 1}
// hello-runner.js

const hello = require('./hello');

console.log(hello); // {a: 1}

This works. but, direct assignment to exports variable doesn't work.

// hello.js file
exports = {a: 1}
// hello-runner.js
const hello = require('./hello');
console.log(hello); // { } 

猜你喜欢

转载自blog.csdn.net/angle_jian/article/details/81773667