Простое использование экспорта,
// -- 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.
Аналогичное использование 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.
Аналогичный вывод.
Итак, в чем разница? 🤔
Экспорт - это всего лишь маленький помощник module.exports. В конечном итоге ваш модуль возвращает вызывающей стороне module.exports, а не экспорт. Все, что делает экспорт, - это собирает свойства и прикрепляет их к module.exports
НО…
Если что-то уже прикреплено к module.exports, все, что связано с экспортом, игнорируется.
// -- hello.js module.exports = { hi: function() { console.log('hi'); }, }; // ALERT - this won't be exported. exports.bye = function() { console.log('bye'); };
Что, если мы присвоим значение module.exports или exports?
// hello.js file module.exports = {a: 1} // hello-runner.js const hello = require('./hello'); console.log(hello); // {a: 1}
Это работает. но прямое присвоение переменной экспорта не работает.
// hello.js file exports = {a: 1} // hello-runner.js const hello = require('./hello'); console.log(hello); // { } 💥💥💥
^^ Мы ничего не экспортировали, потому что переменная экспорта была переназначена и не ссылается на module.exports.
// -- hello.js file exports.hi = function(){ console.log('hi'); } module.exports.bye = function(){ console.log('bye'); }
Это работает. Мы экспортировали как hi
, так и bye
функции.
Подробнее - http://www.hacksparrow.com/node-js-exports-vs-module-exports.html