export default和export的使用方法


Node中

導出

向外導出成員,使用module.exports和exports

module.exports = {}

導出多個成員(必須是在對象中)

foo.js

exports.a = 123
exports.b = 'hello'
exports.c = function () {
    console.log('ccc')
}
exports.d = {
    foo: 'bar'
}

main.js

var fooExports = require('./foo')
console.log(fooExports) //{ a: 123, b: 'hello', c: [Function], d: { foo: 'bar' } }

導出單個成員(拿到的就是:函數、字符串)

foo.js

module.exports = 'hello'

main.js

var fooExports = require('./foo')
console.log(fooExports) //'hello'

以下情況會被覆蓋

foo.js

module.exports = 'hello'

//后者會覆蓋前者
module.exports = function (x, y) {
    return x + y
}

main.js

var fooExports = require('./foo')
console.log(fooExports) //[Function]

也可以這樣來導出多個成員

module.exports = {
    add: function () {
        return x + y
    },
    str: 'hello'
}

exports與module.exports是相同的

console.log(exports === module.exports)     //true

為什么exports與module.exports兩者相同,但是使用 exports = 'foo'  最后得到的還是一個空對象。是因為最后模塊的返回值是module.exports而不是exports,所以給exports直接賦值,exports丟失了之前對象的引用關系,指向了另一個字符串,所以最后是拿不到'foo'的

exports與module.exports總結

每個模塊中都有一個module對象,module對象中有一個exports對象,我們可以把需要導出的成員都掛載到module.exports接口對象中,也就是module.exports.xxx = xxx的方式,但是每次都這樣做很麻煩,所以Node為了方便,同時在每個模塊中都提供了一個成員exports,exports === module.exports。所以對於之前的方式可以簡寫成exports.xxx = xxx。當一個模塊需要導出單個成員時,必須使用 module.exports = xxx 的方式,不可使用exports = xxx 。因為每個模塊最終向外導出的是module.exports,而exports只是module.exports的一個引用,所以即便為exports = xx 重新賦值,並不能影響module.exports 。但是有一種賦值方式比較特殊,就是exports = module.exports,這個會重新建立引用關系。

導入

Node中導入模塊
const 名稱 = require('模塊標識符')

require具體加載規則鏈接

在ES6中

規定了如何導入和導出模塊
導入:
import 模塊名稱 from '模塊標識符'
import '標識路徑'
導出,使用export default和export暴露

export default

export default向外暴露的成員可以使用任意的變量來接收
//test.js
export default {
    name: 'zs',
    age: 10
}

//main.js
import m1 from './test'
//m1 為一個包含 name 和 age 屬性的對象
在一個模塊中,只能使用export default向外暴露一次
// test.js
export default {
    name: 'zs',
    age: 10
}

export default {
    name: 'xiaoming',
    age: 10
}

//會報錯`Only one default export allowed per module`  

export

在一個模塊中可以同時使用 export default 和 export 暴露成員
使用 export 向外暴露的成員只能使用 {} 接收,這種情況叫做 按需導出
// test.js
export default {
    name: 'zs',
    age: 10
}

export var title = "小星星"
//這樣使用不會報錯

//main.js
import m1, { title } from './test'
一個模塊中可以同時使用多個 export
//test.js
export var title = "小星星"
export var content = '哈哈哈'

// main.js
import { title,content } from './test'
如果想在引用時改變名稱,可以通過 as
import { title as title123,content } from './test'
注意成套使用


免責聲明!

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



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