レガシーなRailsアプリにとりえあずReact, TypeScript入れたときのメモ
react-railsのgemは使いたくなかったので、使わない方式です。
- webpackerでReactとTypeScriptをインストール
$ bundle exec rails webpacker:install:react $ bundle exec rails webpacker:install:typescript
- tsconfig.jsonを修正してSyntheticDefaultImportsを有効にする
"allowSyntheticDefaultImports": true
- 生成されたファイルの拡張子を変更
mv hello_react.jsx hello_react.tsx
- ファイルを編集
// Run this example by adding <%= javascript_pack_tag 'hello_react' %> to the head of your layout file, // like app/views/layouts/application.html.erb. All it does is render <div>Hello React</div> at the bottom // of the page. import React from 'react' import ReactDOM from 'react-dom' import { Hello } from './components/pages/Hello' document.addEventListener("DOMContentLoaded", () => { ReactDOM.render( <Hello/>, document.body.appendChild(document.createElement("div")), ) })
- erbにタグ記述
<%= javascript_pack_tag 'hello_react' %>
※jsxの時に起動してしまってると、変なキャシュが動いててtsxでエラーが出るということが発生した。serverを立ち上げ直すなどしたらなおった。
既存Railsアプリに後からReactとTypeScriptを導入する | もふもふ技術部
Webpacker で React + TypeScript - Qiita
以上