ES6核心內容之新特性

import export

ES6 module的其他高級用法

//content.js
export default 'A cat'    
export function say(){
    return 'Hello!'
}    
export const type = 'dog' 

上面可以看出,export命令除了輸出變量,還可以輸出函數,甚至是類(react的模塊基本都是輸出類)

//index.js
import { say, type } from './content'  
let says = say()
console.log(`The ${type} says ${says}`)  //The dog says Hello

這裏輸入的時候要注意:大括號裏面的變量名,必須與被導入模塊(content.js)對外接口的名稱相同。

如果還希望輸入content.js中輸出的默認值(default), 可以寫在大括號外面。

//index.js
import animal, { say, type } from './content'  
let says = say()
console.log(`The ${type} says ${says} to ${animal}`)  
//The dog says Hello to A cat

修改變量名
此時我們不喜歡type這個變量名,因爲它有可能重名,所以我們需要修改一下它的變量名。在es6中可以用as實現一鍵換名。

//index.js
import animal, { say, type as animalType } from './content'  
let says = say()
console.log(`The ${animalType} says ${says} to ${animal}`)  
//The dog says Hello to A cat

模塊的整體加載

除了指定加載某個輸出值,還可以使用整體加載,即用星號(*)指定一個對象,所有輸出值都加載在這個對象上面。

//index.js

import animal, * as content from './content'  
let says = content.say()
console.log(`The ${content.type} says ${says} to ${animal}`)  
//The dog says Hello to A cat
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章