benjamn / recast

JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
MIT License
4.99k stars 349 forks source link

babel parser cannot preserve formatting for parts in some case but Esprima does #1296

Open zoeyzhao19 opened 1 year ago

zoeyzhao19 commented 1 year ago

codesandbox

I am doing the same test between babel and esprima, but it confused me that a semicolon is append to a import statement with babel parser after I do some modification and print, but esprima does not image

Expected result (as esprima does):

import { defineConfig } from "foo"
    export default defineConfig({})

I found the doc said

Whenever Recast cannot reprint a modified node using the original source code, it falls back to using a generic pretty printer. So the worst that can happen is that your changes trigger some harmless reformatting of your code.

But also

When you call recast.parse, it makes a shadow copy of the AST before returning it to you, giving every copied AST node a reference back to the original through a special .original property. This information is what enables recast.print to detect where the AST has been modified, so that it can preserve formatting for parts of the AST that were not modified

So in my side, I might think different parser should not have caused different formatting through recast.parse

This is also related to a magicast issue

Is there any better explaination or it's expected? Thanks.