Skip to content

[Nodejs] module.exports 與 exports 的差別

Published: at 09:02 AM (2 min read)

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


舉例來說: 有一個 player.js

[javascript]

var players = [];

function getPlayers() {

return players;

}

function addPlayer(player) {

players.push(player);

}

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

[/javascript]

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

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

[javascript] var player = require(’./player’);

player.addPlayer(‘playerOne’); console.log(player.getPlayers()); // [‘playerOne’] [/javascript]

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

[javascript]

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;

[/javascript]

[javascript] var player = require(’./player’);

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

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

[javascript] var exports = module.exports = {}; [/javascript]

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

參考資料:

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


Previous Post
[javascript] 取網址 get 的 值(key-value),get query key/value
Next Post
[test] Nightwatch.js debug 血淚史