2

I was trying to modify JavaScript source code by:

  1. parse source code with @babel/babylon and get the AST
  2. traverse AST with babel-traverse and do some modifications where needed
  3. turn AST back to JavaScript source code

The first two steps is pretty simple. But I stuck on turning AST back to source code.

I did some search, and only find examples to transform AST down to lower version JavaScript code.

Any suggestions?

aztack
  • 4,376
  • 5
  • 32
  • 50
  • Isn't this the process that every transpiler uses? – Bergi Dec 26 '17 at 10:08
  • @Bergi, I was trying to transform AST back to it's original form (ES2015 synatx), not transpile it into older syntax – aztack Dec 26 '17 at 10:16
  • I mean that the process of turning back the AST into code is the same everywhere. Whether it transpiles to different JS versions or not only depends on the modifications done in step 2. (Afaik, you can even run Babel without doing any transformations). How did the examples you found do it? Can you link them? – Bergi Dec 26 '17 at 10:28
  • @Bergi, As you said, if I don't provide `babylon.parse` with any plugin, after modify AST, babel-generate will turn AST back to what I want, right? (because no plugin do the transformation). here is the link: [Understanding asts ...](https://www.sitepoint.com/understanding-asts-building-babel-plugin/) – aztack Dec 26 '17 at 11:14
  • Yes, in general `generate(parse(code)) == code` (the identity transform). Or, according to that article, `babel.transform(code, {plugins:[]}).out == code`. – Bergi Dec 26 '17 at 11:29
  • @Bergi GREAT! Thanks! – aztack Dec 26 '17 at 11:58
  • This is exactly the process babel-core already covers for you. Have you explored writing a Babel plugin? – loganfsmyth Dec 26 '17 at 21:10
  • @loganfsmyth, I read some code and articles about writing Bebel plugin. – aztack Dec 27 '17 at 03:21

0 Answers0