LoginSignup
3
1

More than 1 year has passed since last update.

Laravel6.2で「Hello React!」を表示するまで躓いた話

Posted at

はじめに

個人開発で、Reactを触ってみたいと思い、LaravelにReactをインストールしてコンポーネントを読み込み、ブラウザで Hello React!と表示させるまでに躓いたので忘備録として手順をまとめていきます。

今回、参考にさせて頂いた記事です。

Laravelのインストールは完了していたので、Reactのインストールから説明します。

Reactのインストール

①Laravelのプロジェクトで下記コマンドを実行する。
composer require laravel/ui 1.*
参考記事の通りにすると、composer require laravel/uiだが、バージョン関係のエラーが発生するので上記のようにしました。

②次に、php artisan ui reactを実行。私の場合はここで下記のようなエラーが発生したので

laravelプロジェクト/resources/sass not such file or directory

cd resources  //laravelプロジェクト/resources/に移動
mkdir sass      //sassフォルダを作成

上記コマンドを実行して、php artisan ui reactを再度実行すると、下記のようにReactのスカフォールドのインストールが無事成功しました。

React scaffolding installed successfully.
Please run "npm install && npm run dev" to compile your fresh scaffolding.
Authentication scaffolding generated successfully.

Laravelでは、初期のスカフォールドはVueで設定されているのですが、ちゃんとReactに切り替わっているかどうかファイル構成(laravelプロジェクト/resources)でも確認してみます。

実行前

resources
├── assets
│   ├── js
│   │   ├── app.js
│   │   ├── bootstrap.js
│   │   ├── components
│   │   │   └── Example.vue
│   └── sass
│       ├── app.scss
│       └── _variables.scss

実行後

resources
├── assets
│   ├── js
│   │   ├── app.js
│   │   ├── bootstrap.js
│   │   ├── components
│   │   │   └── Example.js
│   └── sass
│       ├── app.scss
│       └── _variables.scss

「Example.vue」が「Example.js」に切り替わっています。
これで、php artisan ui reactの役割は果たせたので、インストールメッセージにもある通り、npm install && npm run devを実行してみます。

npm install
npm run dev

上記のように実行しようとすると npm run devを実行した時点で下記のようなエラーが発生。

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/user/.npm/_logs/2020-12-23T08_06_14_550Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/user/.npm/_logs/2020-12-23T08_06_14_712Z-debug.log

エラーメッセージで検索してみるとピンポイントな解決方法が出てこなかったのですが、npm run devを実行した時のエラー解決方法として下記コマンドを実行している記事が多かったので試してみる。

rm -rf node_modules  (node_moduleを削除)
npm cache clear --force (キャッシュを削除)
npm install (インストールし直し)
npm run dev 再度実行

上記手順でコマンドを実行していくと、さっきまでのエラーは発生しなくなったのですが下記のようなエラーが発生。

Error: mix.react() is now a feature flag. Use mix.js(source, destination).react() instead
   at React.register (F:\Server\work\reactlaravel\lrpc1\node_modules\laravel-mix\src\components\React.js:15:19)
   at Object.components.<computed> [as react] (F:\Server\work\reactlaravel\lrpc1\node_modules\laravel-mix\src\components\ComponentRegistrar.js:118:53)
   at Object.<anonymous> (F:\Server\work\reactlaravel\lrpc1\webpack.mix.js:14:5)
   at Module._compile (F:\Server\work\reactlaravel\lrpc1\node_modules\v8-compile-cache\v8-compile-cache.js:192:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
   at Module.load (internal/modules/cjs/loader.js:985:32)
   at Function.Module._load (internal/modules/cjs/loader.js:878:14)
   at Module.require (internal/modules/cjs/loader.js:1025:19)
   at require (F:\Server\work\reactlaravel\lrpc1\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
   at module.exports (F:\Server\work\reactlaravel\lrpc1\node_modules\laravel-mix\setup\webpack.config.js:3:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ development: `mix`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional >logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\info\AppData\Roaming\npm-cache\_logs\2021-01-06T04_36_25_320Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! 

エラーメッセージで検索すると下記の参考記事を発見。
https://stackoverflow.com/questions/65590280/laravel-8-installation-npm-run-dev-error
laravelプロジェクト(この部分は皆様のLaravelインストールディレクトリ名に合わせる)/package.json を確認する。

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "@babel/preset-react": "^7.0.0",
        "axios": "^0.25.0",
        "bootstrap": "^4.0.0",
        "bootstrap-sass": "^3.3.7",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^6.0.41",//この部分
        "lodash": "^4.17.4",
        "popper.js": "^1.12",
        "react": "^16.2.0",
        "react-dom": "^16.2.0",
        "resolve-url-loader": "^5.0.0",
        "sass": "^1.49.0",
        "sass-loader": "^12.4.0"
    }
}

上記のようにlaravel-mixのバージョンが6になっていると、webpack.mix.jsの記述を以下のように変更しないといけないそうなので、変更してみます。

変更前

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

変更後

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

上記のように変更して、再度npm run devを実行すると下記のように成功メッセージが出力されました!

Compiled Successfully in 9076ms
webpack compiled successfully

次にwelcome.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">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app"></div> //idの値は、後述するApp.js内で利用します。(この部分が、Reactで設定する内容を表示させる為に必要です)
</body>
</html>

次に laravelプロジェクト/resource/js/app.jsファイルを以下のように書き換える。

require('./bootstrap');

require('./components/App');//このjsファイルは後ほど作成。

最後に、先ほど更新したapp.jsファイルで、読み込むApp.jsファイルを作成します。

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

function App() {
    return <h1>Hello React!</h1>;
}

if (document.getElementById('app')) {
    ReactDOM.render(<App />, document.getElementById('app'));
}

下記部分で、先程定義したwelcome.blade.phpのidがappとなっている箇所に、Hello React!を表示させる関数を呼び出しています。
ReactDOM.render(<App />, document.getElementById('app'));

下記2点のファイル更新を反映させる為に、再度npm run dev実行する。
・laravelプロジェクト/resource/js/app.js
・laravelプロジェクト/resource/js/components/App.js

ブラウザで確認するが、Hello React!が表示されていない、、
この時点で、Laravelのbladeから、Reactのコンポーネントを読み込む方法が合っているのかどうか、色々調べたりしたのですが、知人からアドバイスを頂きスーパーリロードを実行してみると以下のようにHello React!が表示されました!!

スクリーンショット 2022-01-27 8.59.51.png

ブラウザのキャッシュの更新が出来ていないという初歩的なミスで躓きましたが、無事にHello React!が表示されて良かったです。

おわりに

環境構築は、参考記事を執筆されている方の使用環境と自分の使用環境が違ったりすると、参考記事通りに行かず
躓いてしまう場面が多々あったので、その都度調べて腑に落ちるまで理解しながら進めていくことが大切だと改めて感じました。

Reactを使用した機能で実装したいことがあるので、実装を進めていきながらよりReactの事について深掘りしていけたらと思います。

ここまで閲覧して頂きありがとうございます!

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