ES6的export與Nodejs的module.exports比較

來源:互聯網
上載者:User

標籤:last   其他   檔案   OLE   class   輸出   es6   default   export   

首先我們要明白一個前提,CommonJS模組規範和ES6模組規範完全是兩種不同的概念。

CommonJS模組規範

Node應用由模組組成,採用CommonJS模組規範。

根據這個規範,每個檔案就是一個模組,有自己的範圍。在一個檔案裡面定義的變數、函數、類,都是私人的,對其他檔案不可見。

CommonJS規範規定,每個模組內部,module變數代表當前模組。這個變數是一個對象,它的exports屬性(即module.exports)是對外的介面。載入某個模組,其實是載入該模組的module.exports屬性。

var x = 5;var addX = function (value) {  return value + x;};module.exports.x = x;module.exports.addX = addX;

上面代碼通過module.exports輸出變數x和函數addX。

require方法用於載入模組。

var example = require(‘./example.js‘);console.log(example.x); // 5console.log(example.addX(1)); // 6
exports 與 module.exports

為了方便,Node為每個模組提供一個exports變數,指向module.exports。這等同在每個模組頭部,有一行這樣的命令。

var exports = module.exports;

於是我們可以直接在 exports 對象上添加方法,表示對外輸出的介面,如同在module.exports上添加一樣。注意,不能直接將exports變數指向一個值,因為這樣等於切斷了exports與module.exports的聯絡。

ES6模組規範

不同於CommonJS,ES6使用 export 和 import 來匯出、匯入模組。

// profile.jsvar firstName = ‘Michael‘;var lastName = ‘Jackson‘;var year = 1958;export {firstName, lastName, year};

需要特別注意的是,export命令規定的是對外的介面,必須與模組內部的變數建立一一對應關係。

// 寫法一export var m = 1;// 寫法二var m = 1;export {m};// 寫法三var n = 1;export {n as m};
export default 命令

使用export default命令,為模組指定預設輸出。

// export-default.jsexport default function () {  console.log(‘foo‘);}

ES6的export與Nodejs的module.exports比較

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.