[Nodejs] module.exports 與 exports 的差別

如果沒有接觸過 commonJs 這類可以將 js 模組化為檔案的開發者,剛開始寫 Nodejs 時可能會有點不懂 module.exportsexports 的差別


舉例來說: 有一個 player.js

var players = [];

function getPlayers() {

  return players;

}

function addPlayer(player) {

  players.push(player);

}

module.exports = {
  addPlayer: addPlayer,
  getPlayers: getPlayers
};

這樣就產生了一個 player.js 這個模組

如果今天 main.js 想要使用這個模組,就可以透過 require 來引入模組
如:

var player = require('./player');

player.addPlayer('playerOne');
console.log(player.getPlayers()); // ['playerOne']

再來我們看看使用 exports 新增一個 removePlayer 的方法

var players = [];

function getPlayers() {

  return players;

}

function addPlayer(player) {

  players.push(player);

}

function removePlayer(player) {
  players = players.filter((val) => val !== player);
}

module.exports = {
  addPlayer: addPlayer,
  getPlayers: getPlayers
};

exports.removePlayer = removePlayer;

var player = require('./player');

player.addPlayer('playerOne');
console.log(player.getPlayers());  // ['playerOne']
player.removePlayer('playerOne');  //player.removePlayer is not a function

原因是在模組裡面其實會預先幫你做

var exports = module.exports = {};

預設當我們使用 exports 其實也代表更改了 module.exports
但當直接使用 module.exports = {...} 其實也就更改了模組對外公開的物件,因此更改 exports 時無法更改到 module.exports

 

參考資料:

https://program365.wordpress.com/2015/07/02/understanding-module-exports-and-exports-in-node-js/

Leave a Reply