LoginSignup
9
9

More than 5 years have passed since last update.

Browserify + Reactify + watchify + gulpでReactの開発をする

Posted at

目的

Scalaのweb frameworkであるxitrumでReactを使いたい。Reactで利用できるライブラリはnpmのmoduleが殆んどなので、moduleをNode.jsを使わずに使いたい(var foo = require('foo');を使いたい)。

Browserifyの導入

Browserifyのmoduleを使うことでNode.jsを使わすにrequireが使える。
Browserifyはrequireしているnpm moduleを1つのjsファイルにまとめてくれる。つまり、requireがmoduleのjsに置き換わる。

BrowserifyだけだとJSXを変換できないので、Reactify moduleを使用する。Reactifyはbrowserifyコマンドの-tオプションで reactify を指定することでJSXの変換とreact moduleの追加をやってくれる。これで JSXTransformer.jsreact.jsscriptタグで読み込む必要がなくなる。

BrowserifyとReactifyだけだと毎回browserifyコマンドを叩いで手動でjsファイルを変換する必要があるので、ファイルの変更を監視して差分を自動で変換してもらうことにする。

そこで watchifygulp moduleを使用する。

こちらを参考にgulpfile.jsを作成した。

これでgulp jsとするだけで対象のjsファイルを監視して、自動で変換してくれる。

gulpfile.js
'use strict';

var watchify = require('watchify');
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');
var reactify = require('reactify');

// add custom browserify options here
var customOpts = {
    entries: ['./src/main.js'],
    transform: [reactify],
    debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));

gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
    return b.bundle()
        // log errors if they happen
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source('app.js'))
        // optional, remove if you don't need to buffer file contents
        .pipe(buffer())
        // optional, remove if you dont want sourcemaps
        .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
        // Add transformation tasks to the pipeline here.
        .pipe(sourcemaps.write('./')) // writes .map file
        .pipe(gulp.dest('../../../../public/js'));
}

全体の導入は、こちらを参考にしました。

xitrumでReactを利用する

xitrumへの導入はここを参考にしました。

上記のexampleを参考にすれば、全体の構成はわかるかと思います。

npm moduleは src/resource/react で管理する。

npm moduleは package.json を作って。moduleのインストール時に、--save-devオプションを付けることでインストールしたmoduleを管理する。これで git clone した時も、必要なmoduleが管理できて便利。

JSXファイルは src/resource/react/src に置く。

変換され一つにまとめられたjsファイルは public/js の下に出力する。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9