Phoenix – React 連携

2019年12月2日 Posted by PURGE

Phoenix Project 作成

$ mix phx.new ProjectName --app project_name --no-ecto

npm モジュールインストール

$ cd ProjectName/assets/node_modules/
$ npm install --save @babel/preset-react
$ npm install --save @babel/polyfill
$ npm install --save react react-dom redux react-redux
$ npm install --save react-router-dom
$ npm install --save connected-react-router history
$ npm install --save redux-thunk
$ npm install --save axios
$ npm install --save redux-form react-hook-form
$ npm install --save react-bootstrap
$ npm install --save history
$ npm install redux-saga --save

.babelrc 設定

assets/.babelrc
{
"presets": [
"@babel/preset-env",
"@babel/react"
]
}

エントリポイント(index.js)の変更

$mv assets/js/app.js assets/js/index.js
index.js

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
<div>
Hello React!!
</div>,
document.getElementById('root')
);

webpack.config.js

entry: {
'./js/index.js': glob.sync('./vendor/**/*.js').concat(['./js/index.js'])
},
output: {
filename: 'index.js',
path: path.resolve(__dirname, '../priv/static/js')
},

index.eex の変更

lib/project_name_web/templates/page/index.eex

<section class="row">
<article class="column">
<div id="root"></div>
</article>
</section>

index.jsパスの変更

lib/project_name_web/templates/layout/app.eex

<script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/index.js") %>"></script>

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です