Using ReactJS with Babel and ES6

I wanted to create this post shortly after the last post about Setting up ES6+Babel+Gulp, but it got delayed for some reasons. Anyways ..

Though it is not very complicated to setup ReactJS to work with Babel, there are a few non-obvious things you need to be aware of, specifically the absence of  auto-binding in ReactJS when coded in ES6. Let’s create a small NodeJS project using Gulp –

Install following packages –

npm install gulp gulp-connect vinyl-source-stream browserify babelify babel-preset-es2015 react react-dom babel-preset-react --save-dev

In addition to packages installed in the last post, here we are installing react, react-dom and babel-preset-react packages.

The directory structure is similar to one in the previous post, except that we add views folder for JSX files.

ES6ReactJSBabelTest
  -- build
  -- src
    -- js
       -- views
    -- html
  -- gulpfile.js

Gulp ‘build’ task is modified to add ‘react’ preset to babelify and add jsx extension to browserify (we want browserify to process .jsx files in addition to .js files) Continue reading “Using ReactJS with Babel and ES6”

Setting up ES6+Babel+Gulp

ECMAScript 6 (ES6, specification at http://www.ecma-international.org/ecma-262/6.0/) has many nice features, but presently not all browsers support ES6. However you can still develop your applications in ES6 and make it run in all browsers. For this you need what is called as transpiler – which converts ES6 code to ES5, which all browsers understand currently.

One of the popular transpiler is Babel . In this post we will see how to use Node.js (https://nodejs.org/), Gulp.js (https://gulpjs.com/), Browserify (http://browserify.org/)  to compile ES6 code to ES5.

Gulp is a build tool for Node.js applications. Browserify resovles ‘require’ modules of Node.js and bundles all modules in one file. We will first use browserify to combine all our JS code in one file and then feed the output to babelify to translate the code to ES5. Structure of this sample project is as follows –

ES6BabelTest
  -- build
  -- src
    -- js
    -- html
  -- gulpfile.js

Not all the files are folders are shown above, for example package.json and node_modules folder are not shown.

Continue reading “Setting up ES6+Babel+Gulp”

Social