Node.js中exports和module.exports的區別詳解(附源碼)

module.exports 對象是由模塊系統創建的。在我們自己寫模塊的時候,需要在模塊最後寫好模塊接口,聲明這個模塊對外暴露什麼內容,module.exports 提供了暴露接口的方法。

1、返回一個JSON Object

var app = {
    name: 'app',
    version: '1.0.0',
    sayName: function(name){
        console.log(this.name);
    }
}
module.exports = app;

這種方法可以返回全局共享的變量或者方法。
調用方法:

var app = require('./app.js');
app.sayName('hello');//hello

或者這樣用:

var func1 = function() {
   console.log("func1");
};
 
var func2 = function() {
   console.log("func2");
};
 
exports.function1 = func1;
exports.function2 = func2;

調用方法爲:

var functions = require("./functions");
functions.function1();
functions.function2();

2、返回一個構造函數

CLASS.js:

var CLASS = function(args){
     this.args = args;
}
module.exports = CLASS;

調用:

var CLASS = require('./CLASS.js');
varc = new CLASS('arguments');

3、返回一個實例對象:

//CLASS.js
var CLASS = function(){
    this.name = "class";
}
CLASS .prototype.func = function(){
    alert(this.name);
}
module.exports = new CLASS();

調用:

var c = require('./CLASS.js');
c.func();//"class"

exports和module.exports

可是這兩種使用起來到底有什麼區別呢???

看了很多文章,長篇大論,始終沒有講清楚區別,自己也是看了很多,終於搞清楚了,給大家分享一下

根據使用方法來說

通常exports方式使用方法是:

exports.[function name] = [function name]

moudle.exports方式使用方法是:

moudle.exports= [function name]

這樣使用兩者根本區別是

**exports **返回的是模塊函數
**module.exports **返回的是模塊對象本身,返回的是一個類


使用上的區別是

exports的方法可以直接調用
module.exports需要new對象之後纔可以調用

二話不說,擼代碼!

1. exports方式

先創建一個exports_mode.js

var sayHello = function(){    console.log('hello')
}
exports.sayHello = sayHelloconsole.log(exports); 
console.log(module.exports);

然後寫一個test.js調用下試試看

var exports_mode = require('./exports_mode')
exports_mode.sayHello()

輸出:

 

exports_mode.png

發現此時exports和module.exports對象輸出的都是一個sayHello方法,
爲什麼module.exports也有exports方法了,簡單點理解就是

exports是module.exports的一個引用,exports指向的是module.exports

我們來驗證下,在exports_mode.js最後一行添加一句代碼

var sayHello = function(){    console.log('hello')
}
exports.sayHello = sayHelloconsole.log(exports); 
console.log(module.exports); 
console.log(exports === module.exports);


結果輸出.png

發現console.log(exports === module.exports)返回的是true,
說明exports和module.exports是同一個對象

下來看看

2. module.exports方式
首先創建module_exports_mode.js

var sayHello = function(){    console.log('hello')
}module.exports = sayHelloconsole.log(module.exports); 
console.log(exports); 
console.log(exports === module.exports);


然後測試一下

var module_export_mode = require('./module_exports_mode')
module_export_mode.sayHello()


控制檯輸出.png

發現輸出報錯了!

爲什麼呢,因爲我們的調用方式錯了,一開始就說到了

**module.exports **返回的是模塊對象本身


正確的調用

var module_export_mode = require('./module_exports_mode')new module_export_mode()


控制檯輸出.png

 

同時我們可以看到,輸出的module.exports對象內容就是一個[Function],在javascript裏面是一個類

使用這樣的好處是exports只能對外暴露單個函數,但是module.exports卻能暴露一個類

我們把module_exports_mode.js擴展一下

var xiaoming = function(name){    this.name = name    this.sayHello = function(){        return 'hello '+this.name
    }    this.sayGoodBye = function(){        return 'goodbye '+this.name
    }
}module.exports = xiaomingconsole.log(module.exports); 
console.log(exports); 
console.log(exports === module.exports);


然後測試

var xiaoming = require('./module_exports_mode')var xiaoming = new xiaoming('Lucien')console.log(xiaoming.sayHello())console.log(xiaoming.sayGoodBye())


控制檯輸出.png

使用方法和javascript的類創建對象一毛一樣

exports.[function name] = [function name]
moudle.exports= [function name]

以上就是這兩種方式的使用區別。

等等,還沒完。。。

上面有提到

exports是module.exports的一個引用,exports指向的是module.exports

也就是說exports的方法module.exports也是一定能完成的

exports.[function name] = [function name]
moudle.exports= [function name]

所以,在使用上

** moudle.exports.[function name]   = [function name] **
**  是完全和 **
** exports.[function name] = [function name]  **
**  相等的   **

但是我們通常還是推薦使用exports.[function name],各司其職,代碼邏輯清晰

 
exports、module.exports 和 export、export default 到底是咋回事
前言

難得有空,今天開始重新規範的學習一下node編程。
但是引入模塊我看到用 require的方式,再聯想到咱們的ES6各種export 、export default。

阿西吧,頭都大了....

頭大完了,那我們坐下先理理他們的使用範圍。

require: node 和 es6 都支持的引入
export / import : 只有es6 支持的導出引入
module.exports / exports: 只有 node 支持的導出

這一刻起,我覺得是時候要把它們之間的關係都給捋清楚了,不然我得混亂死。話不多少,咱們開幹!!

node模塊


Node裏面的模塊系統遵循的是CommonJS規範。
那問題又來了,什麼是CommonJS規範呢?
由於js以前比較混亂,各寫各的代碼,沒有一個模塊的概念,而這個規範出來其實就是對模塊的一個定義。

CommonJS定義的模塊分爲: 模塊標識(module)、模塊定義(exports) 、模塊引用(require)

先解釋 exports 和 module.exports
在一個node執行一個文件時,會給這個文件內生成一個 exports和module對象,
而module又有一個exports屬性。他們之間的關係如下圖,都指向一塊{}內存區域。

exports = module.exports = {};複製代碼

內存結構示意圖

那下面我們來看看代碼的吧。

//utils.js
let a = 100;
 
console.log(module.exports); //能打印出結果爲:{}
console.log(exports); //能打印出結果爲:{}
 
exports.a = 200; //這裏辛苦勞作幫 module.exports 的內容給改成 {a : 200}
 
exports = '指向其他內存區'; //這裏把exports的指向指走
 
//test.js
 
var a = require('/utils');
console.log(a) // 打印爲 {a : 200}複製代碼

從上面可以看出,其實require導出的內容是module.exports的指向的內存塊內容,並不是exports的。
簡而言之,區分他們之間的區別就是 exports 只是 module.exports的引用,輔助後者添加內容用的。

用白話講就是,exports只輔助module.exports操作內存中的數據,辛辛苦苦各種操作數據完,累得要死,結果到最後真正被require出去的內容還是module.exports的,真是好苦逼啊。

其實大家用內存塊的概念去理解,就會很清楚了。

然後呢,爲了避免糊塗,儘量都用 module.exports 導出,然後用require導入。

ES中的模塊導出導入
說實話,在es中的模塊,就非常清晰了。不過也有一些細節的東西需要搞清楚。
比如 export 和 export default,還有 導入的時候,import a from ..,import {a} from ..,總之也有點亂,那麼下面我們就開始把它們捋清楚吧。

export 和 export default
首先我們講這兩個導出,下面我們講講它們的區別

export與export default均可用於導出常量、函數、文件、模塊等
在一個文件或模塊中,export、import可以有多個,export default僅有一個
通過export方式導出,在導入時要加{ },export default則不需要
export能直接導出變量表達式,export default不行。
下面咱們看看代碼去驗證一下

testEs6Export.js

'use strict'
//導出變量
export const a = '100';  
 
 //導出方法
export const dogSay = function(){ 
    console.log('wang wang');
}
 
 //導出方法第二種
function catSay(){
   console.log('miao miao'); 
}
export { catSay };
 
//export default導出
const m = 100;
export default m; 
//export defult const m = 100;// 這裏不能寫這種格式。複製代碼


index.js

//index.js
'use strict'
var express = require('express');
var router = express.Router();
 
import { dogSay, catSay } from './testEs6Export'; //導出了 export 方法 
import m from './testEs6Export';  //導出了 export default 
 
import * as testModule from './testEs6Export';//as 集合成對象導出
 
 
 
/* GET home page. */
router.get('/', function(req, res, next) {
  dogSay();
  catSay();
  console.log(m);
  testModule.dogSay();
  console.log(testModule.m); // undefined , 因爲  as 導出是 把 零散的 export 聚集在一起作爲一個對象,而export default 是導出爲 default屬性。
  console.log(testModule.default); // 100
  res.send('恭喜你,成功驗證');
});
 
module.exports = router;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章