lyft/react-javascript-to-typescript-transform

Pretty output: run the program through prettier

mohsen1 opened this issue · 5 comments

TypeScript printer is not printing the most beautiful code. We can run the code through prettier as second phase of processing to get nicer output.

@mohsen1 I use prettier after running this transform, All codes looks OK except the empty line won't be reserved.

I think it's hard to pass the transformed AST to prettier to format since it uses typescript-eslint-parser.

The workaround I used is using jsdiff to compare original code and the result and add the empty lines back.

prettier APIs work with raw text too. We can add prettier as a secondary phase of processing here

For the CLI we want to proxy all CLI flags of prettier

@mohsen1 What I mean is:

original file:

import * as React from 'react';

export default class MyComponent extends React.Component {
    render() {
        return <button onClick={this.onclick.bind(this)} />;
    }

    onclick() {
        // ...
    }
}

ts transform result: (empty lines are stripped now)

import * as React from 'react';
export default class MyComponent extends React.Component<{
    }, {
    }> {
    render() {
        return <button onClick={this.onclick.bind(this)}/>;
    }
    onclick() {
        // ...
    }
}

use prettier to format the ts result:(prettier won't add empty lines)

import * as React from 'react';
export default class MyComponent extends React.Component<{}, {}> {
    render() {
        return <button onClick={this.onclick.bind(this)} />;
    }
    onclick() {
        // ...
    }
}

Prettier won't add empty lines for us, it will just respect the empty lines in original file.

Preserving empty lines is pretty difficult. I remembered somewhere in TypeScript issue tracker they mentioned why they don't preserve the empty lines

We can probably do it as a transform phase on top of prettier

Yeah, right now the printer doesn't really take node positions into account (see here and below in that file) so all the newlines will disappear and the formatting will be according to the printer.

Side note: FWIW, you might want to consider checking out ts-simple-ast. It can be used to more easily do code manipulations in TypeScript. It will do the edits on the source file text directly so it won't cause any formatting changes—new lines will be preserved. I'm slowly working on refactoring the writing so that it can be easily configured with formatting options. The downside is that it's not as performant as doing transformations on the AST directly, but it's not too bad.

Also, this react-javascript-to-typescript-transform is an excellent idea! It's good to be able to automate helping people switch over to TypeScript.