LoginSignup
0
0

More than 1 year has passed since last update.

LaravelにReactとTypeScriptを導入する

Posted at

前提

Laravelでプロジェクトを作成していて、nodeはインストール済みの想定で進めていきます。

TypeScriptをインストールする

webpack.mix.js(webpackのラッパーライブラリ)を下記のように編集する

mix.ts('resources/ts/index.tsx', 'public/js')
    .sass('resources/sass/app.scss', 'public/css');

先ほどの編集内容を反映させる

npm install

プロジェクト内にnode_modulesディレクトリが作成されていればOK。
一旦下記コマンドでビルドする。

npm run prod

package.jsonにwebpack.mix.jsで編集した内容の不足分が記載される(typescriptとsass)

Reactをインストールする

npm i -D react react-dom @types/react @types/react-dom
npm install

package.jsonに追記されているか確認する。

React用のTypeScriptの設定ファイルを作成する

tsc --init --jsx react

すると...
tsconfig.jsonが作成される。

動作確認

①webpack.mix.jsに記載した下記を作成する。
■resources/ts/index.tsx

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

const App = () => {
  return (
    <h1>Laravel SPA</h1>
  )
}

ReactDOM.render(
    <App />,
    document.getElementById('app')
)

■resources/sass/app.scss
→resources/css/app.cssをリネームする

②下記コマンドでビルドする

npm run prod

③resources/views/welcome.blade.phpをresources/views/index.blade.phpへリネームする
下記のように書き直す

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
        <link rel="stylesheet" href="{{ mix('/css/app.css') }}">
    </head>
    <body>
        <div id="app"></div>
    </body>
    <script src="{{ mix('/js/index.js') }}"></script>
</html>

④web.phpでrouteをwelcomeからindexへ変更する

⑤キャッシュ対策でファイルパスにパラメーターを付与する
webpack.mix.jsに下記を追記する

if (mix.inProduction()) {
    mix.version()
}

⑥ビルトインサーバーを起動してlocalhost:8000へアクセスする

php artisan serve

編集した内容が表示されていることを確認できました!

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