2 ES6模塊
ES6模塊基于文件蔗彤,一個文件就是一個模塊剖毯。
ES6模塊支持異步模塊加載。
關(guān)鍵字:import
和export
堂淡。
導(dǎo)入和導(dǎo)出
在變量赁温、函數(shù)和類等標(biāo)識符之前使用export
。
export const message='hello world';
在模塊最后一行導(dǎo)出淤齐。
const message='hello world';
function sayHello(){
return message+'!';
}
export {message,sayHello};
在另一文件中導(dǎo)入股囊。
import {message,sayHello} from 'Bear.js'
導(dǎo)入模塊中導(dǎo)出的全部的標(biāo)識符。
import * from 'Bear.js'
默認(rèn)導(dǎo)出
使用一個標(biāo)識符代表整個模塊的導(dǎo)出更啄。仍然可以導(dǎo)出其他標(biāo)識符稚疹。
export default class Bear{
constructor(name){
this.name=name;
}
}
export function compareBear(bear1,bear2){
return bear1.name==bear2.name;
}
導(dǎo)入默認(rèn)導(dǎo)出的內(nèi)容,不需要花括號,也可以指定任意名稱内狗。
import WiredBear from 'Bear.js';
import {compareBear} from 'Bear.js';
可以更簡明一些怪嫌。
import WiredBear,{compareBear} from 'Bear.js';
重命名
重命名export
。
function niHao(){
return 'hello';
}
export {niHao as sayHello};
import {sayHello} from 'Greeting.js';
重命名import
柳沙。
function niHao(){
return 'hello';
}
export niHao;
import {niHao as sayHello} from 'Greeting.js';