美文网首页babel
babel插件安利

babel插件安利

作者: 发发呆哟 | 来源:发表于2020-05-04 19:23 被阅读0次

    插件,让代码更优雅

    1. babel-plugin-transform-decorators-legacy

    这几天在补高阶组件的相关知识,对于高阶组件的引用方式,感觉有些别扭,若是需要引用多个高阶组件,必定需要套娃。

    根据官方说明,这个插件适用于babel@6.x,如果你正在使用babel@7.x,可以使用@babel/plugin-proposal-decorators

    安装和使用

    $ npm install --save-dev babel-plugin-transform-decorators-legacy

    在package.json中配置

    "babel": {
        "presets": [
          "react-app"
        ],
        "plugins": [
          "transform-decorators-legacy"
        ]
    },
    
    注意点

    如果在项目中还是用了transform-class-properties,请保证transform-decorators-legacy在前

    // right
    "plugins": [
      "transform-decorators-legacy",
      "transform-class-properties"
    ]
    
    react中的实际使用

    我自己在使用高阶组件的时候,会用到这个插件,让代码看起来更优雅,不过最常用的应该是withRouter,毕竟路由切换是最常用的业务

    // 原有写法
    import React from 'react';
    import { usernameHoc } from '@/hoc'
    
    const GoodBye = props => {
        return <div>GoodBye {props.username}</div>
    }
    
    export default usernameHoc(GoodBye);
    
    // 新的写法
    import React from 'react';
    import { usernameHoc } from '@/hoc'
    
    @usernameHoc
    const GoodBye = props => {
        return <div>GoodBye {props.username}</div>
    }
    
    export default GoodBye;
    

    2. babel-plugin-transform-class-properties

    接上一个插件中提到的transform-class-properties这个插件也是react中文站介绍PropTypes时推荐的,可以试用一下。

    官方定义

    该插件可转换es2015静态类属性以及使用es2016属性初始化程序语法声明的属性。(转化为各大浏览器的支持的es5语法)

    安装和使用

    npm install --save-dev babel-plugin-transform-class-properties

    "babel": {
        "presets": [
          "react-app"
        ],
        "plugins": [
          "transform-decorators-legacy",
          "transform-class-properties"
        ]
    },
    
    react中的实际使用

    可以将props检测和defaultProps声明写在class内部,更优雅。

    class Para extends React.Component {
    
        constructor(props){
            super(props)
            this.state = {
                para: '123'
            }
        }
    
        static defaultProps = {
            name: 'stranger'
        }
        
        static propTypes = {
            name: PropTypes.string.isRequired
        }
    
        render(){
            return <div>
                {this.props.name}
                <p>{this.state.para}</p>
            </div>
        }
    }
    

    相关文章

      网友评论

        本文标题:babel插件安利

        本文链接:https://www.haomeiwen.com/subject/bwuyghtx.html