LoginSignup
0
0

More than 3 years have passed since last update.

続Laravel5.5でもVue.jsっぽくReact.js x TypeScriptを部分的に導入する

Last updated at Posted at 2021-04-29

概要

Laravel5.5でもVue.jsっぽくReact.jsを部分的に導入するの続きで、TypeScriptを導入します。

TypeScript導入

$ npm install -D typescript @types/node @types/react @types/react-dom

tsconfig.json作成

$ ./node_modules/.bin/tsc --init
tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "noImplicitAny": false,
    "jsx": "react",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "exclude": [
    "vendor"
  ]
}

Laravel-Mixアップグレード

webpackが4系じゃないとコンパイルがうまくいかないらしい

package.json
.
.
.
        "laravel-mix": "^5.0",
.
.
.
$ npm i

ts-loaderインストール

$ npm i ts-loader@^8 -D

webpack.mix.js編集してtsを使用

webpack.mix.js
mix.ts('resources/assets/js/app.tsx', 'public/js');

resources/assets/js/app.tsx作成

resources/assets/js/app.tsx
import * as React from 'react';
import { render } from 'react-dom';

type Props = {
    title: string | null
}
const Example: React.FC<Props> = ({ title }) => (
    <div className="container">
        <div className="row">
            <div className="col-md-8 col-md-offset-2">
                <div className="panel panel-default">
                    <div className="panel-heading">Example Component</div>

                    <div className="panel-body">
                        {title}
                    </div>
                </div>
            </div>
        </div>
    </div>
);

const Element = document.getElementById('example');
if (Element) {
    const title = Element.getAttribute('title');
    render(<Example title={title} />, document.getElementById('example'));
}

resources/views/welcome.blade.phpでprops設定

welcome.blade.php
.
.
.
    <body>
        <div class="flex-center position-ref full-height">
            <div id="example" title="ts-react"></div>
        </div>

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

コンパイルと画面表示

$ npm run dev
$ php artisan serve

スクリーンショット 2021-04-29 22.29.15.png

参考

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