Hanami + FuseBox + React.js


About

React の練習をしたくなったので前の記事の続きとして React.js を導入します。

Setup

hanami g appで新しくアプリを作ります。(名前はなんでも良い)

shell
hanami g app react

Assets不使用にして、FuseBoxインストールまでやったら、表示するページを作ります。今回はTypeScriptで書かないのでfuse.jsの設定が少し変わります。

apps/react/fuse.js
const path = require('path');
const publicPath = path.resolve(__dirname, '..', '..', 'public');

const { FuseBox } = require('fuse-box');
const fuse = FuseBox.init({
  homeDir : 'frontend',
  target  : 'browser@es6',
  output  : `${publicPath}/$name.js`,
  useTypescriptCompiler: true,
  plugins : [
  ],
  shim : {
  }
});
fuse.bundle('react-app').instructions('> application.js').watch('frontend/**');
fuse.run();

shell
hanami g action react page#index
apps/react/config/routes.rb
root to: 'page#index'
apps/react/templates/page/index.html.haml
%h1 Index

%p Hello, with index!
apps/react/templates/application.html.haml
!!!
%html
  %head
    %title React
  %body
    = yield
  %script{ type: 'text/javascript', src: 'react-app.js' }
apps/react/frontend/application.js
console.log('Hello FuseBox.');

yarn build後、hanami sにてlocalhost:2300/reactにアクセスしてコンソールに表示があればOK。

Babel setup

apps/reactディレクトリ内で以下を実行する。

shell
yarn add babel-core babel-preset-es2015 babel-plugin-transform-react-jsx -D
apps/react/fuse.js
- const { FuseBox } = require('fuse-box');
+ const { FuseBox, BabelPlugin } = require('fuse-box');
...
+ plugins : [
+     BabelPlugin({
+       presets : ["es2015"],
+       plugins : [
+         ["transform-react-jsx"]
+       ]
+     })
+   ],
...
- fuse.bundle('react-app').instructions('> application.js').watch('frontend/**');
+ fuse.bundle('react-app').instructions('> application.jsx').watch('frontend/**');

application.jsapplication.jsxに改名しておく。

React.js setup

Babel setup と同様にapps/reactディレクトリ内で以下を実行する。

shell
yarn add react react-dom
apps/react/frontend/application.jsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>Hello, React.js!</h1>,
  document.getElementById('hello')
);
apps/react/templates/page/index.html.haml
- %h1 Index
- 
- %p Hello, with index!
+ #hello

あとはyarn buildhanami sで確認してエラーなく表示されていれば成功。

おまけ

コードの参考はこちらへどうぞ。

参考