そのひぐらし

ニートになりたい

おはよう世界

Railsのproduction環境でReactを使った時につまったメモ

デプロイ時にassets:precompileで下記のようなエラー吐いた。
どうやらjsxファイルがうまく認識されていない。
結論はconfigの書き方が間違っていた。

** Invoke assets:precompile (first_time)
** Invoke assets:environment (first_time)
** Execute assets:environment
** Invoke environment (first_time)
** Execute environment
rake aborted!
ExecJS::ProgramError: Unexpected character '`' (line: 3, col: 18, pos: 98)

Error
    at new JS_Parse_Error (/tmp/execjs20150609-19949-kcuuaqjs:2359:10623)
    at js_error (/tmp/execjs20150609-19949-kcuuaqjs:2359:10842)
    at parse_error (/tmp/execjs20150609-19949-kcuuaqjs:2359:12560)
    at Object.next_token [as input] (/tmp/execjs20150609-19949-kcuuaqjs:2359:17582)
    at next (/tmp/execjs20150609-19949-kcuuaqjs:2359:18900)
    at vardefs (/tmp/execjs20150609-19949-kcuuaqjs:2359:25834)
    at var_ (/tmp/execjs20150609-19949-kcuuaqjs:2359:25996)
    at /tmp/execjs20150609-19949-kcuuaqjs:2359:21785
    at /tmp/execjs20150609-19949-kcuuaqjs:2359:19957
    at block_ (/tmp/execjs20150609-19949-kcuuaqjs:2359:24599)new JS_Parse_Error ((execjs):2359:10623)
js_error ((execjs):2359:10842)
parse_error ((execjs):2359:12560)
Object.next_token [as input] ((execjs):2359:17582)
next ((execjs):2359:18900)
vardefs ((execjs):2359:25834)
var_ ((execjs):2359:25996)
(execjs):2359:21785
(execjs):2359:19957
block_ ((execjs):2359:24599)

File: README — Documentation for react-rails (1.0.0)
をみて、config/application.rbに下記を追記して解決した。

config.react.jsx_transform_options = {
  harmony: true,
  strip_types: true, # for removing Flow type annotations
}

development.rbとproduction.rbにはそれぞれ、 config.react.variant = :development config.react.variant = :production を書く。

因みにエラー吐いてたときの状態でローカルでassets:precompileしたらいけたし、 問題なくJSXは認識されてたから何でだろう。。 →ローカルでは生のcss,jsファイルを使うのに対し、プロダクションはassets:precompileして圧縮したファイルを使う。おそらくローカルでassets:precompileしていけたのは、そもそも圧縮したファイルを使うように設定されていなかったとみてる。

備考
harmonyオプションはES6,7の書式を有効にするオプションで引っかかっていたのはそのES6,7の書式の部分だった。