//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.
未完待续