When using React, you can use ES6 to make your life more easy. First of all you need a transpiler, Babel is the way to go as of today. It transpiles ES6 with JSX (Facebook’s special syntax for React).
We first make a new gulp task and load our libraries. We make a new browserify bundle by calling browserify. If you want to use the .jsx extension you can provide browserify the .jsx extension name, this way browserify will by default recognize .jsx files without you explicitly having to define it. Our entry file is main.js, from this file we import other files.
So a quick recap:
- Make browserify bundle (a.k.a collect al the files)
- Transform files with babelify from ES6 + JSX to plain ES5
- Bundle them into one file
Now that we can handle ES6 + JSX code, how should your React code itself look? Well for React classes you can now do:
This is nice because you now have a “real” ES6 class, so you can use inheritance, constructors and getter/setter methods. However, you cannot use mixins, at Facebook they are currently working on a better solution for that. I use mixins a lot so I use a more “classic” approach:
This looks almost the same as the ES5 version, so why use ES6 anyway?
- You can use the ES6 import/export syntax
- You can still use the method shorthand like in classes
Note: Babelify actually compiles the import statements to the NodeJS require syntax. This allows Browserify to leverage the NodeJS module system for resolving dependencies.
I think unless your development environment makes it impossible to run the transpilations, using ES6 is a no brainer. It makes you future proof, write cleaner code and it is fun!