IK.AM

@making's tech note


React.jsのアプリをbrowserify/gulpで作る

🗃 {Programming/JavaScript/Framework/React.js}
🏷 Browserify 🏷 Gulp 🏷 JavaScript 🏷 React.js 
🗓 Updated at 2015-03-03T15:06:00Z  🗓 Created at 2015-03-03T15:06:00Z   🌎 English Page

React.jsを使うときのひな形としてメモ

とりあえず小さく。

プロジェクト作成

$ mkdir -p hello-react/src
$ cd hello-react
$ npm init
$ npm install --save-dev browserify gulp vinyl-source-stream react reactify

gulpfile.js作成

var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var reactify = require('reactify');

gulp.task('browserify', function () {
    return browserify('./src/index.js', {
        debug: true,
        transform: [reactify]
    })
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./'));
});

gulp.task('watch', function () {
    gulp.watch('src/*.js', ['browserify']);
});

HelloWorldアプリ

src/components.js

var React = require('react');

var HelloWorld = React.createClass({
    render: function () {
        return (
            <div>
                <h1>React.js Sample</h1>
                <Display />
            </div>
        );
    }
});

var Display = React.createClass({
    render: function () {
        return (<p>Hello World!</p>);
    }
});

module.exports = HelloWorld;

src/index.js

var React = require('react');
var HelloWorld = require('./components.js');

React.render(
    <HelloWorld />,
    document.getElementById('example')
);

hello.html

<!DOCTYPE html>
<html>
<head lang="ja">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="example"></div>
<script src="bundle.js"></script>
</body>
</html>

ビルド

$ gulp browserify

hello.htmlを開けば

image

開発中は

$ gulp watch

でjsが変更されたらビルドされる。

ファイル圧縮したい場合は、こちらの設定を追加すれば良い。

rest.jsを使う

前の記事で紹介したように、HTTPクライアントでrest.jsを使いたい。

$ npm install --save-dev rest

で、components.jsを以下のように修正

var React = require('react');
var rest = require('rest');
var mime = require('rest/interceptor/mime');

var client = rest.wrap(mime);

var HelloWorld = React.createClass({
    render: function () {
        return (
            <div>
                <h1>React.js Sample</h1>
                <Display />
            </div>
        );
    }
});

var Display = React.createClass({
    getInitialState: function () {
        return {id: 0, content: 'Now Loading...'};
    },
    componentDidMount: function () {
        client({path: 'http://rest-service.guides.spring.io/greeting'})
            .then(function (response) {
                this.setState(response.entity);
            }.bind(this));
    },
    render: function () {
        return (
            <table>
                <tr><th>ID</th><td>{this.state.id}</td></tr>
                <tr><th>CONTENT</th><td>{this.state.content}</td></tr>
            </table>);
    }
});

module.exports = HelloWorld;

再度ビルドして、hello.htmlを開くと、

image

できたくさい。

動くサンプル

これでReact.jsを使ったアプリのひな形ができた。


✒️️ Edit  ⏰ History  🗑 Delete