在es6中,通过规范的形式,规定了es6中如何导入和导出模块
es6中导入模块,使用
import 模块名称 from ‘模块标识符’ 或者
import ‘路径’
的方式。
导出模块使用export default 和export 向外暴露成员
//--------------------------------------------------------------------------------
例如
导出模块:
test.js:
//普通导出
export {
name:'zs',
age: 20
}
//默认导出的模块,让使用者自己命名,且只能使用default导出一次。
export default {
name:'zs',
age: 20
}
//导出的其他模块
export var title = "小星星"
export var content = "哈哈哈"
导入模块(按照上面导出的顺序)
main.js
import {name,age} from './test.js
import m1 from './test.js
import {title,content} from './test.js'
console.log(m1)
console.log(title+"------"+content)
注意:使用export暴露的成员,只能使用{}的方式来接收,这种形式,叫做按需导出
同时,如果某些成员,在import的时候不需要,则可以不在{}中定义
注意:使用export导出的成员,必须严格按照导出时的名称,使用{}接收。
如果非要给导出的非默认模块起别名,使用as起别名:
import m1,{title as title1,content as content1} from './test.js'
console.log(m1)
console.log(title1+"------"+content1)
//-----------------------------------------------------------------------------------------------
Node中
在node中使用module.export 和 exports来暴露成员
使用 var 名称 = require(‘模块标识符’) 来导入 和es6中别弄混了