05 Sep 2015, 00:00

ES6, React & Browserify

ES6, React & Browserify

Browserify is a lightweight build tool for JS, you can start ‘require’ modules with zero configuration, Thanks to Babelify, you can start writing ES6 code (via Babel) write away,

Here’s a proof how simple it is,

Lets create a package.json file and install minimal dependencies

npm init
npm install --save react
npm install --save-dev browserify babelify watchify

Lets give Browserify a hint that it should perform code transformation via babelify by adding this json tag to package.json

"browserify": {
  "transform": [
    "babelify"
  ]
}

It can also be nice to just type npm start when developing, so lets add a start script to package.json as well

“start”: “watchify –extension=js -o bundle.js index.js & python -m SimpleHTTPServer”,

Note: Watchify is not mandatory but it’s great tool for watching your code changes and auto rebuild when a change gets discovered.

Lets put the simplest index file ever:

<html>
  <body>
    <script type="text/javascript" src="bundle.js"></script>
  </body>
</html>

Here’s a simple ES6 class with React.

import React from 'react';

class Hello extends React.Component {
  constructor(props) {
    super(props)
    this.state = {count: props.initCount}
    this.tick = this.tick.bind(this)
  }

  tick () {
    this.setState({count: this.state.count + 1});
  }
  render(){
    let { name } = this.props
    let { count } = this.state
    return (
      <button onClick={this.tick}>Hello {name} {count}</button>
    );
  }
}

React.render(<Hello name="Stranger" initCount={5}/>, document.body)

Running the code:

npm start

Open browser http://localhost:8000

To summary:

1) Browserify is lightweight build tool, it handles modularity by understanding require 2) Labelify is a plugin for Browserify, it takes care of transpilling ES6 code to ES5 via Babel. 3) Thanks to Babel & React integration, there’s no need for any extra plugins to perform JSX transformations.