Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform plugin vs Syntax plugin in Babel

I want to use Class properties in my webpack setup. Following along with this book (www.survivejs.com), I noticed the author adds 2 plugins to the .babelrc file: babel-plugin-syntax-class-propertiesas well as babel-plugin-transform-class-properties.

Looking at the babel docs of the syntax-class-properties it states:

Syntax only

This plugin only allows Babel to parse this syntax. If you want to transform it then see transform-class-properties.

What's the difference? And do I need both? My code seem to run fine just with the transform plugin.

like image 516
Sander Garretsen Avatar asked Jan 20 '16 11:01

Sander Garretsen


2 Answers

The transformation is a three step process:

  1. Parse the source code into an AST
  2. Change / transform the AST
  3. Print the AST (convert to source code)

Syntax plugins are necessary for step 1: Proposals such as class properties introduce a new syntax, which cannot be parsed by current JavaScript parsers. Syntax plugins extend the parser so it understands the new syntax.

Example: Imagine I introduce a new token @, such as in

@.foo();

A JavaScript parser wouldn't be able to parse this code into an AST, because currently the @ is invalid in that position. So I'd have to extend the parser to parse it.

Transform plugins are necessary for step 2: Now that the source was parsed, we need to convert the AST nodes of the new feature into something that is valid in current JavaScript.

Example: The @ in my previous example is a new way to refer to this. To make it work in current environments which don't understand @, I need to transform and replace it with this, so that the above example becomes

this.foo();

And do I need both?

If you want to convert your code to ES5, yes.

My code seem to run fine just with the transform plugin.

You might be using a preset of something that already includes the syntax plugin.

like image 164
Felix Kling Avatar answered Oct 17 '22 21:10

Felix Kling


If you look at https://babeljs.io/docs/plugins/#transform it says

Transform plugins will enable the corresponding syntax plugin so you don't have to specify both.

Although maybe should add that in all the syntax plugins? Feel free to bring up an issue/PR for it.

like image 42
hzoo Avatar answered Oct 17 '22 21:10

hzoo