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 = '哈哈哈'
//导出函数
export function fun1(num1, num2) {
    return num1 + num2
}
//导出类
export class Person {
    run() {
        console.log('在奔跑')
    }
}

// main.js
import { title, content } from './test'
如果想在引用时改变名称,可以通过 as
import { title as title123,content } from './test'
成套导入
import * as aaa from "./aaa.js";
console.log(aaa.title)

 

注意成套使用
posted @ 2019-03-25 23:51  懒懒同学  阅读(7552)  评论(0编辑  收藏  举报