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

转载于:https://www.cnblogs.com/studyhtml5/p/7154169.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值