React + gulp using ES6

ECMAScript 6 (ES6) is the upcoming version of the ECMAScript standard, so it would make a lot of sense to start using it today. In this post I show how ES6 can be used in combination with React and Gulp.

Gulpfile.js
The task runner needs to convert Reacts JSX to valid javascript and also convert ES6 to ES5 at the same time:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var gulp = require('gulp'),
    to5Browserify = require('6to5-browserify'),
    source = require('vinyl-source-stream'),
    browserify = require('browserify');

gulp.task("default", function () {
  browserify({ debug: true })
    .transform(to5Browserify)
    .require('main.jsx', { entry: true })
    .bundle()
    .pipe(source('all.js'))
    .pipe(gulp.dest('./dist'));
});

index.html
The main html file loads the compiled javascript and provides the entry point/element for React (id = ‘content’).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!doctype html>

<html>
    <head></head>
    
    <body>
        <main id="content"></main>
        <script src="all.js"></script>        
    </body>
</html>

main.jsx
In this file the React component Foo is loaded and rendered

1
2
3
4
var React = require('react');
var Foo = require('./Foo');

React.render(<Foo />, document.getElementById('content'));

Foo.jsx
This is the React component using ES6

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
'use strict';

var React = require('react');

class Foo {
    getDefaultProps() {
        return {
             message: 'No message'   
        }
    }
    
    getInitialState() {
        return {
            message: 'Click me!'
        };
    }
    
    componentWillMount() {}
    
    render() {        
        return <div onClick={this.onClick}>{this.state.message}</div>
    }
    
    onClick() {
        this.setState({message: 'You clicked me'});
    }
}

module.exports = React.createClass(Foo.prototype)

Comments are closed.