LoginSignup
163
148

More than 5 years have passed since last update.

Node.jsのexportsとmodule.exportsの違いについてのメモ

Posted at

既にいくつか記事がありましたが、自分の中で整理するためにメモ

参考

結論

  • 公式ドキュメントに「もし exports と module.exports の間の関係が魔法のように 見えるなら、exports を無視して module.exports だけを使うようにしてください」とあるので今いち違いが分からない場合、module.exportsをとりあえず使うということで良さそう
  • クラスのようなものを作成するような場合にはmodule.exportsを使えば良い(例えばコンストラクタを使うなども)
  • 関数だけモジュール化したい場合にはexportsを使う事で実現できる
  • exportsが指定されていない関数についてはrequireしても利用できない

exportsを試す

以下のような3つの関数を定義する

util.js
exports.sayAdd = function(a, b) {
  say(a + b);
}

exports.saySubtract = function(a, b) {
  say(a - b);
}

say = function(word) {
  console.log(word);
}

say関数についてはexportsを付与していない

上記utilを使うファイルを作成して実行してみる

main.js
var util = require('./util');

util.sayAdd(1, 2); // 3
util.saySubtract(2, 1); //1
util.say // error. util.say is not a function

exportsした関数については利用可能だが、exportsしていない関数については利用できない。ただし、同じファイル(util.js)の関数からはexportsしていない関数へのアクセスも可能となっている

module.exportsを試す

映画のクラス?を作ってみる

movie.js
// コンストラクタ
var Movie = function(title) {
  this.title = title;
}

Movie.prototype.sayTitle = function() {
  say(this.title);
}

say = function(word) {
  console.log(word);
}

module.exports = Movie;

これを使ってみる。

main2.js
var Movie = require('./movie');

var movieA = new Movie('Star Wars');
movieA.sayTitle(); //Star Wars

var movieB = new Movie('Mad Max');
movieB.sayTitle(); // Mad Max
movieB.say(); // error. movieB.say is not a function

こんな感じでコンストラクタで映画のタイトルを指定するようなクラスのようなものを作成する事ができた。

以下のように書く事もできる。

movie.js
module.exports = function(title) {
  this.title = title;

  this.sayTitle = function() {
    say(this.title);
  }
}

function say(word) {
  console.log(word);
}
163
148
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
163
148