LoginSignup
1
0

More than 5 years have passed since last update.

react_railsでes6を使うときのプラクティス

Posted at

前にdraftjsをrailsで利用する記事を書きましたが、あまりしっくり来ていなかったので試行錯誤した結果を記します。

結論から言うとjsのトランスパイルはgulpで行うことにしました、railsの設定系ファイルと完全に分離して表側のアセットを管理できるようになったので今のところ使い勝手は良いです。

やることとしてはgulpでes6で記述されたreact_componentをトランスパイルするだけなので結構シンプルです。

前回draft-jsを使いましたがよりreactに最適化されているっぽいやつがあったので今回はこちらを使っています。

動作環境

rails 5系 or 4系
npm
package.json参照

手順

  • 必要なnpmpackageのインストール
  • react_component作成
  • gulpfile作成とトランスパイル

実装

  • 必要なnpmpackageのインストール

下記パッケージのインストール

package.json

"dependencies": {
    "browserify": "~> 10.2.4",
    "coffee-script": "^1.12.3",
    "draft-js": "^0.10.0",
    "glob": "^7.1.1",
    "gulp": "^3.9.1",
    "gulp-babel": "^6.1.2",
    "gulp-coffee": "^2.3.3",
    "gulp-plumber": "^1.1.0",
    "gulp-uglify": "^2.0.1",
    "gulp-watch": "^4.3.11",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-draft-wysiwyg": "^1.7.0",
    "vinyl-source-stream": "^1.1.0"
  }

  • react_component作成

どんなコンポーネントでも良いのですが、react-draft-wysiwygで試してみます。react_railsのヘルパーを使いたいのでwindow.DraftEditorと最後に書いてますがもっといい方法を知っている方がいたら教えてくださいm(__)m

DraftEditor.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { Editor } from 'react-draft-wysiwyg';
import {EditorState} from 'draft-js';


class DraftEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onEditorStateChange = (editorState) => this.setState({editorState});
  }
  render() {
    const { editorState } = this.state;
    return (<Editor
      editorState={editorState}
      onEditorStateChange={this.onEditorStateChange}
    />)
  }
}
window.DraftEditor = DraftEditor
  • gulpfile作成とトランスパイル

最後にes6で書かれたreact_componentをトランスパイルした上でuglifyで1つにします。今回はappと並列にreact_component用のディレクトリを作成しトランスパイル後のjsファイルはreact_railsの規約に則りasset以下のcomponentディレクトリに吐き出します。
coffeescriptなのはなんとなく気分なので特に理由はないです笑

gulpfile.coffee
gulp          = require 'gulp'
babel         = require 'gulp-babel'
browserify    = require 'browserify'
source        = require 'vinyl-source-stream'
glob          = require 'glob'
plumber       = require 'gulp-plumber'

gulp.task 'build', ->
  files = glob.sync './components/*.{js,jsx,coffee}'
  browserify
    entries: files,
    debug: true
  .transform 'babelify'
  .bundle()
  .pipe plumber((err) ->
      console.log(err)
      this.emit('end')
    )
  .pipe source 'bundle.js'
  .pipe gulp.dest 'app/assets/javascripts/components'

gulp.task 'watch', ->
  gulp.watch('./components/*.{js,jsx,coffee}', ['build'])

gulp.task 'default', ['build', 'watch']

所感

新しいツールの導入が多くある程度労力はかかりますがレールから外れると割り切ると途端に楽になります。

githubにあげておいたので参考までにどうぞ

1
0
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
1
0