一句話說清楚NodeJS中module.exports和exports的區別

關於這個問題NodeJS的官方文檔中有一句很精闢的解釋:

What’s the difference between module.exports and exports?
The first exposes the object it points to. The latter exposes the properties of the object it points to.

翻譯過來就是說,module.exports是直接導出整個對象,而exports導出的是對象中的屬性。以下通過兩個簡單的例子可以直觀的看清楚這兩種方式的區別。

module.exports

這種方式最好理解,直接導出一個對象,如下所示:

// item.js
const car = {
  brand: 'Ford',
  model: 'Fiesta'
}

module.exports = car

// app.js
const item = require('./item')
console.log(item)

// output
D:\workspace\idea\nodejs_demo>node app.js
{ brand: 'Ford', model: 'Fiesta' }

可以看到require進來的就是module.exports導出的對象。

exports

這種方式導出的對象會成爲最終導出的對象的一個屬性,如下:

// items.js
const car = {
    brand: 'Ford',
    model: 'Fiesta'
}

const computer = {
    brand: 'Dell',
    model: 'OptiPlex'
}

exports.car = car   // 成爲導出對象的car屬性
exports.computer = computer  // 成爲導出對象的computer屬性

// app.js
const items = require('./items')
console.log(items)

// output
D:\workspace\idea\nodejs_demo>node app.js
{
  car: { brand: 'Ford', model: 'Fiesta' },
  computer: { brand: 'Dell', model: 'OptiPlex' }
}

可以發現,exports.car = car 導出的car對象實際上成爲了導出對象的car屬性,exports.computer = computer 導出的computer對象成爲了導出對象的computer屬性。

此時回過頭來看下面這兩句話應該就能體會到這兩種方式的本質區別了:

What’s the difference between module.exports and exports?
The first exposes the object it points to. The latter exposes the properties of the object it points to.

原話出自NodeJS官方文檔: https://nodejs.dev/learn/expose-functionality-from-a-nodejs-file-using-exports

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章