打鐵要趁熱老厌,今天我們繼續(xù)講es6其他幾個(gè)非常有用的新特性趣斤。
import export
這兩個(gè)家伙對(duì)應(yīng)的就是es6自己的module功能纽窟。
我們之前寫(xiě)的Javascript一直都沒(méi)有模塊化的體系酒来,無(wú)法將一個(gè)龐大的js工程拆分成一個(gè)個(gè)功能相對(duì)獨(dú)立但相互依賴(lài)的小工程啡浊,再用一種簡(jiǎn)單的方法把這些小工程連接在一起。
這有可能導(dǎo)致兩個(gè)問(wèn)題:
一方面js代碼變得很臃腫毙籽,難以維護(hù)
另一方面我們常常得很注意每個(gè)script標(biāo)簽在html中的位置洞斯,因?yàn)樗鼈兺ǔS幸蕾?lài)關(guān)系,順序錯(cuò)了可能就會(huì)出bug
在es6之前為解決上面提到的問(wèn)題坑赡,我們得利用第三方提供的一些方案,主要有兩種CommonJS(服務(wù)器端)和AMD(瀏覽器端么抗,如require.js)毅否。
而現(xiàn)在我們有了es6的module功能,它實(shí)現(xiàn)非常簡(jiǎn)單蝇刀,可以成為服務(wù)器和瀏覽器通用的模塊解決方案螟加。
ES6模塊的設(shè)計(jì)思想,是盡量的靜態(tài)化,使得編譯時(shí)就能確定模塊的依賴(lài)關(guān)系捆探,以及輸入和輸出的變量然爆。CommonJS和AMD模塊,都只能在運(yùn)行時(shí)確定這些東西黍图。
傳統(tǒng)的寫(xiě)法
首先我們回顧下require.js的寫(xiě)法曾雕。假設(shè)我們有兩個(gè)js文件:index.js和content.js,現(xiàn)在我們想要在index.js中使用content.js返回的結(jié)果,我們要怎么做呢助被?
首先定義:
//content.js
define('content.js', function(){
? ? return 'A cat';
})
然后require:
//index.js
require(['./content.js'], function(animal){
? ? console.log(animal);? //A cat
})
那CommonJS是怎么寫(xiě)的呢剖张?
//index.js
var animal = require('./content.js')
//content.js
module.exports = 'A cat'
ES6的寫(xiě)法
//content.js
export default 'A cat'? ?
export function say(){
? ? return 'Hello!'
}? ?
export const type = 'dog'
以上我把三者都列出來(lái)了,再也不用擔(dān)心我寫(xiě)混淆了...
ES6 module的其他高級(jí)用法
//content.js
export default 'A cat'? ?
export function say(){
? ? return 'Hello!'
}? ?
export const type = 'dog'
上面可以看出揩环,export命令除了輸出變量搔弄,還可以輸出函數(shù),甚至是類(lèi)(react的模塊基本都是輸出類(lèi))
//index.js
import { say, type } from './content'?
let says = say()
console.log(`The ${type} says ${says}`)? //The dog says Hello
這里輸入的時(shí)候要注意:大括號(hào)里面的變量名丰滑,必須與被導(dǎo)入模塊(content.js)對(duì)外接口的名稱(chēng)相同顾犹。
如果還希望輸入content.js中輸出的默認(rèn)值(default), 可以寫(xiě)在大括號(hào)外面。
//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
修改變量名
此時(shí)我們不喜歡type這個(gè)變量名褒墨,因?yàn)樗锌赡苤孛脑晕覀冃枰薷囊幌滤淖兞棵T趀s6中可以用as實(shí)現(xiàn)一鍵換名貌亭。
//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
模塊的整體加載
除了指定加載某個(gè)輸出值柬唯,還可以使用整體加載,即用星號(hào)(*)指定一個(gè)對(duì)象圃庭,所有輸出值都加載在這個(gè)對(duì)象上面锄奢。
//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
通常星號(hào)*結(jié)合as一起使用比較合適。
終極秘籍
考慮下面的場(chǎng)景:上面的content.js一共輸出了三個(gè)變量(default, say, type),假如我們的實(shí)際項(xiàng)目當(dāng)中只需要用到type這一個(gè)變量剧腻,其余兩個(gè)我們暫時(shí)不需要拘央。我們可以只輸入一個(gè)變量:
import{type}from'./content'
由于其他兩個(gè)變量沒(méi)有被使用,我們希望代碼打包的時(shí)候也忽略它們书在,拋棄它們灰伟,這樣在大項(xiàng)目中可以顯著減少文件的體積。
ES6幫我們實(shí)現(xiàn)了儒旬!
不過(guò)栏账,目前無(wú)論是webpack還是browserify都還不支持這一功能...
如果你現(xiàn)在就想實(shí)現(xiàn)這一功能的話(huà),可以嘗試使用rollup.js