LoginSignup
0
0

More than 3 years have passed since last update.

LaravelでReactを使う私的まとめ

Posted at

Laravel Mix

  • フロントエンドのアセットをコンパイル、バンドルしてくれる
  • 中身はwebpackでwebpackの設定をわかりやすく掛けるようにラッピングしてある
  • sass,babelなどは最初から用意されている

バンドル

バンドルとは、束(ねる)、塊などの意味を持つ英単語で、単体でも提供可能な製品やサービスを、複数組み合わせてセットで販売したり、別の製品やサービスに付属して販売、提供することをこのように呼ぶ。
引用:バンドル 【 bundle 】

つまり違うものを組み合わせてくれるってことかな

Laravel Mixの実行

npm run dex

npm run dev を実行すると、
package.jsonに書いてあるスクリプトが実行され、
設定ファイルに記述したコンパイルやバンドルが実行される。

npm run production の場合は圧縮されたファイルが出力される。
引用:Laravel Mixとは?webpackをより便利に、簡単に。Laravel以外でも使えるよ。

npm run watch

関連ファイルを監視する
変更を感知すると自動的に再コンパイル

webpack.mix.jsファイル

Sass

saasメソッドはSassをCSSコンパイル

mix.sass('resources/assets/sass/app.scss', 'public/css');

ページを作ってみる

resource/js/app.js
/**
 * Next, we will create a fresh React component instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

//require('./components/Example'); 
require('./components/index'); //ここを書き換える

次に、すべてのルーティングをindex.balde.phpに集中させる

web.php
Route::get('/{any}', function(){
    return view('index');
})->where('any', '.*'); 

bladeファイルを作成

index.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
  <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Title</title>
</head>
<body>
<div id="root">
    {{-- <example-component></example-component> --}}
</div>

<script src="{{ asset('/js/app.js') }}"></script>
</body>
</html>

これでreact-router-domによるルーティングに対応できました。

参考:LaravelにReactを導入する時の手順〜ルーティングの設定

参考

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