//content.js export default 'A cat' export function say(){ return 'Hello!' } export const type = 'dog'
上面能夠看出,export命令除了輸出變量,還能夠輸出函數,甚至是類(react的模塊基本都是輸出類)react
//index.js import { say, type } from './content' let says = say() console.log(`The ${type} says ${says}`) //The dog says Hello
這裏輸入的時候要注意:大括號裏面的變量名,必須與被導入模塊(content.js)對外接口的名稱相同。webpack
若是還但願輸入content.js中輸出的默認值(default), 能夠寫在大括號外面。es6
//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
實現一鍵換名。web
//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
除了指定加載某個輸出值,還可使用總體加載,即用星號(*
)指定一個對象,全部輸出值都加載在這個對象上面。app
//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
一般星號*
結合as
一塊兒使用比較合適。函數
考慮下面的場景:上面的content.js
一共輸出了三個變量(default, say, type
),假如咱們的實際項目當中只須要用到type
這一個變量,其他兩個咱們暫時不須要。咱們能夠只輸入一個變量:ui
import { type } from './content'
因爲其餘兩個變量沒有被使用,咱們但願代碼打包的時候也忽略它們,拋棄它們,這樣在大項目中能夠顯著減小文件的體積。spa
ES6幫咱們實現了!code
不過,目前不管是webpack仍是browserify都還不支持這一功能...orm
若是你如今就想實現這一功能的話,能夠嘗試使用rollup.js
他們把這個功能叫作Tree-shaking,哈哈哈,意思就是打包前讓整個文檔樹抖一抖,把那些並未被依賴或使用的東西通通抖落下去。。。
看看他們官方的解釋吧:
Normally if you require a module, you import the whole thing. ES2015 lets you just import the bits you need, without mucking around with custom builds. It's a revolution in how we use libraries in JavaScript, and it's happening right now.
未完待續