• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
独秀不爱秀
虽生而平凡,但愿死而非凡
博客园    首页    新随笔    联系   管理    订阅  订阅

Node.js 中 exports 和 module.exports 的区别

  1. 每一个模块中都有一个 module 对象, module 对象中有一个 exports 对象
  2. 我们可以把需要导出的成员都放到 module.exports 这个接口对象中,也就是 module.exports.xxx = xxx 的方式
  3. 但是,这样显得特别麻烦,为了方便操作,在每一个模块中又提供了一个叫 exports 的成员
  4. 所以,有了这样的等式: module.exports === exports
  5. 所以,对于:module.exports.xxx = xxx 的方式等价于 exports.xxx = xxx
  6. 当一个模块需要导出单个成员的时候,必须要使用 module.exports = xxx
  7. 因为每个模块最终向外 return 的是 module.exports,而 exports 只是 module.exports 的一个引用,所以即便你为 exports = xxx 重新赋值,也不会影响 module.exports

重新建立引用关系:

exports = module.exports;

导出多个成员(必须在对象中):

  • 方法一(使用 exports):
        exports.a = 123;
        exports.b = 'hello';
        exports.c = () => {
            console.log('ccc');
        };
        exports.d = {
            foo: 'bar'
        };

     

  • 方法二(使用module.exports):
        module.exports = {
            add: (x, y) => {
                return x + y;
            },
            str: 'hello'
        };

     

导出单个成员(拿到的直接就是 字符串, 数字 等):

  

module.exports = 'hello';

但是的话,因为只能导出单个成员,所以会出现覆盖情况,如下所示:

    module.exports = 'hello';

    // 以这个为准,后者会覆盖前者
    module.exports = (x, y) => {
        return x + y;
    };

 

posted @ 2019-07-07 20:51  小方哥·  阅读(2251)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3