【问题标题】:Code transformer AST to JS代码转换器 AST 到 JS
【发布时间】:2017-02-18 16:33:25
【问题描述】:

我正在尝试编写 js 代码转换器。我需要将 JS 解析成 AST 做一些修改,例如添加一个新的导入声明,然后生成 JS 代码。

目前我在生成 JS 代码时遇到了一些麻烦。装饰器出现在错误的位置,生成器删除了 JSX 周围的括号。

我是这个领域的新手,所以可能我在转换/生成代码时错过了一些选项。

源代码:

// Core
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actions } from '../../actions/navigation';

const mapStateToProps = ({ navigation }) => ({ // eslint-disable-line arrow-body-style
    menuStatus: navigation.get('menuStatus')
});

const mapDispatchToProps = (dispatch) => ({ // eslint-disable-line arrow-body-style
    actions: bindActionCreators({ ...actions }, dispatch)
});

@connect(mapStateToProps, mapDispatchToProps)
export default class Home extends Component {
    render () {
        return (
            <section>
                <h1>Home container!</h1>
            </section>
        );
    }
}

解析/生成的代码:

// Core
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actions } from '../../actions/navigation';

const mapStateToProps = ({ navigation }) => ({ // eslint-disable-line arrow-body-style
  menuStatus: navigation.get('menuStatus')
});

const mapDispatchToProps = dispatch => ({ // eslint-disable-line arrow-body-style
  actions: bindActionCreators({ ...actions }, dispatch)
});

export default @connect(mapStateToProps, mapDispatchToProps)
class Home extends Component {
  render() {
    return <section>
                <h1>Home container!</h1>
            </section>;
  }
}

Demo repository

【问题讨论】:

标签: javascript reactjs babeljs abstract-syntax-tree


【解决方案1】:

这是一个 Babel 错误:https://github.com/babel/babel/issues/4585

如果您希望生成可以保存回文件系统的代码,您可能最好查看JSCodeShift,因为它的目标是在操作代码时保留格式,而 Babel 对现有格式。

【讨论】:

    猜你喜欢
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多