Link
Link

Reputation: 93

After babel/parser generates ast, immediately use babel/generator to output, the results are inconsistent

const { parse } = require('@babel/parser')
const generator = require('@babel/generator')

const source = `const babel = {
  version() {},
  author: ''
};`

const ast = parse(source)

console.log(generator.default(ast).code === source) // false

console.log(generator.default(ast).code)
/*
const babel = {
  version() {},

  author: ''
};
*/

One more space after the version function

I slightly modified the implementation of the version function. From the previous FunctionExpression to the current ArrowFunctionExpression, the result is in line with expectations.

const { parse } = require('@babel/parser')
const generator = require('@babel/generator')

const source = `const babel = {
  version: () => {},
  author: ''
};`

const ast = parse(source)

console.log(generator.default(ast).code === source) // true

What should I do to keep them consistent?

Upvotes: 1

Views: 699

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161517

Babel is focused on performing transformations to the code from the standpoint of programmatic behavior, so it only makes a small amount of effort to reproduce the original formatting. Given that, this is expected behavior.

In the case you're seeing, it appears that the formatting you expect does not match what your Babel version happens to output. If formatting is important, I'd recommend running the code through prettier afterward to give it consistent formatting.

Upvotes: 2

Related Questions