Node js object exports

拜拜、爱过 提交于 2019-12-03 08:17:20

Consider that with require, you gain access to the module.exports object of a module (which is aliased to exports, but there are some subtleties to using exports that make using module.exports a better choice).

Taking your code:

exports.caravan = { month: "july" };

Which is similar to this:

module.exports.caravan = { month: "july" };

Which is similar to this:

module.exports = {
  caravan : { month: "july" }
};

If we similarly "translate" the require, by substituting it with the contents of module.exports, your code becomes this:

var caravan = {
  caravan : { month: "july" }
};

Which explains why you need to use caravan.caravan.month.

If you want to remove the extra level of indirection, you can use this in your module:

module.exports = {
  month: "july"
};

If you want to get via caravan.month then:

module.exports = {
    month: "july"
};

If you want to get the object, use

module.exports = {
  caravan = {
       month: "july"
  }
};

and then get it like this:

var caravan = require("./caravan")

You may also check:

console.log(caravan.caravan.month);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!