ES6 语法之import export

假设我们有两个js文件: index.jscontent.js,现在我们想要在index.js中使用content.js返回的结果

ES6的写法

//index.js
import animal from './content'

//content.js
export default 'A cat'

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

修改变量名

此时我们不喜欢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

通常星号*结合as一起使用比较合适。

笔者在react项目的第一行就是import * as React from "react" 以前一直不理解这种引入有什么用,学习到了ES6语法以后豁然开朗,

以及明白了

export class ButtonGroup extends React.Component<any, any>  中的React 就是指把React的整体模块加载然后继承React.Component
posted @ 2017-07-12 10:35  H5工程师  阅读(906)  评论(0编辑  收藏  举报