LoginSignup
96
92

More than 5 years have passed since last update.

exports と module.exports の違い

Last updated at Posted at 2013-10-30

なんかややこしい解説が多いが、そんなに難しい話ではない。
1. exports = module.exports = {} が予め実行されていて、
2. 最終的に評価されるのは module.exports
ということ。

心配だったら常に module.exports を使えば OK だし、(正しく記述されているコードを)読む時は全部脳内で module.exports と読み替えてしまって良い。

じゃあどこで差が出るのか、なんでややこしい解説がされてるのか。

exports = なんたら という式は、exportsの中身をごっそり入れ替えてしまうので、exports == module.exportsの関係が壊れる。
exports.hoge = 1 はこの関係を崩さない。

歴史的経緯によれば(ぶっちゃけ想像ですが)もともとは exports しか無かった。つまり、

var hoge = require('./hoge');
hoge.foo();
hoge.bar();

という形の使い方しか想定してなかった。
ところが、誰かが new hoge したい、と言い出した。(恐らく他の誰かが new hoge.Hogeとすればいいじゃん、と反論しただろうが、美しくない、と却下された)
exports だけではこれは実現出来ない。そこで、あとから module.exports という記法が追加された。

多分そんなことだろうと思います。想像ですが。

96
92
2

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
96
92