export和export dafault以及exports和moudle.exports的區別
阿新 • • 發佈:2018-11-10
1、import引入依賴包不需要相對路徑,引入其他變數、函式等需要相對路徑
例如:引入依賴包 import axios from 'axios';
引入函式 import appservice from './appservice';
2、使用export丟擲的變數,引入時名稱是丟擲的名稱,不可以自定義
//a.js
export function getList(){};
//b.js
import {getList} from './a.js';
3、使用export default 丟擲的變數,只需要自己起一個名字就行;
//a.js var obj = {name:'liming'}; export default obj; //b.js import aaa from './a.js'; console.log(aaa.name);//輸出'liming'
接下來說一說exports和module.exports的區別
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); // 5
console.log(example.addX(1)); // 6
exports 與 module.exports
為了方便,Node為每個模組提供一個exports變數,指向module.exports。這等同在每個模組頭部,有一行這樣的命令。
var exports = module.exports;
於是我們可以直接在 exports 物件上新增方法,表示對外輸出的介面,如同在module.exports上新增一樣。注意,不能直接將exports變數指向一個值,因為這樣等於切斷了exports與module.exports的聯絡。