zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Python Day23
    Python Day22
    Python Day21
    Python Day20
    Python Day19
    Python Day18
    Python Day17
    Python Day15
    Appium python unittest pageobject如何实现加载多个case
    Appium python Uiautomator2 多进程问题
  • 原文地址:https://www.cnblogs.com/studyhtml5/p/7154169.html
Copyright © 2011-2022 走看看