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;
    };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM