简体   繁体   English

babel/parser生成ast后,马上用babel/generator输出,结果不一致

[英]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 version功能后多一个空格

I slightly modified the implementation of the version function.我稍微修改了 version 函数的实现。 From the previous FunctionExpression to the current ArrowFunctionExpression , the result is in line with expectations.从之前的FunctionExpression到现在的ArrowFunctionExpression ,结果都符合预期。

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?我应该怎么做才能使它们保持一致?

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. Babel 专注于从程序行为的角度对代码执行转换,因此它只需要很少的努力来重现原始格式。 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.在您看到的情况下,您期望的格式似乎与您的 Babel 版本输出的格式不匹配。 If formatting is important, I'd recommend running the code through prettier afterward to give it consistent formatting.如果格式很重要,我建议之后通过prettier运行代码以使其格式一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM