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,這個會重新建立引用關系。
導入
const 名稱 = require('模塊標識符')
在ES6中
import 模塊名稱 from '模塊標識符'
import '標識路徑'
export default
//test.js export default { name: 'zs', age: 10 } //main.js import m1 from './test' //m1 為一個包含 name 和 age 屬性的對象
// test.js export default { name: 'zs', age: 10 } export default { name: 'xiaoming', age: 10 } //會報錯`Only one default export allowed per module`
export
// test.js export default { name: 'zs', age: 10 } export var title = "小星星" //這樣使用不會報錯 //main.js import m1, { title } from './test'
//test.js export var title = "小星星" export var content = '哈哈哈' // main.js import { title,content } from './test'
import { title as title123,content } from './test'