DEV Community

olivertembo
olivertembo

Posted on

React, Typescript with Laravel

Sometimes it is much more convenient to build a monolith up.
I will take you through how I setup my Laravel app with React with Typescript.

For this we will make a simple Laravel, React, Typescript App. We will call it. Laravel-Guava
Technology Stack:

  1. PHP/Laravel
  2. Inertia/Breeze
  3. React/Typescript

I am using a windows with WSL, ubuntu for this. using a mac should be the same experience. 😉

Feel free to fork it make improvements as you like.

Technology: Make sure you have composer, typescript, node, docker installed. If not I'll add a few lines to make it work.

Step One: Install the latest version of Laravel and run it.

curl -s https://laravel.build/<name-of-your-app> | bash
./vendor/bin/sail up later composer-docker up is enough
npm install
npm run install

Initialize typescript in your project. this will create a ts config file. If that doesn't work, install typescript here[https://www.typescriptlang.org/download]

npx tsc --init

these are my configuration for my typescript
{
"compilerOptions": {
"target": "es5",
"module": "es2020",
"moduleResolution": "node",
"baseUrl": "./",
"strict": true, // Enable strict type-checking options
"skipLibCheck": true, // Skip type checking of declaration files
"noImplicitAny": false // Bypass raising errors on
anytype
},
"include": ["resources/js/**/*"] // Frontend paths pattern
}

  1. Install the dependencies
    npm install ts-loader typescript --save-dev
    composer require laravel/breeze --dev
    php artisan breeze:install react

  2. Configure Laravel Mix
    Initial Laravel installation comes with a boilerplate JavaScript entry point, which needs to get converted into TypeScript. All you need is to rename .js to .ts.


-resources/js/app.js
+resources/js/app.tsx

configure webpack.config.js to resolve typescript extensions
`
const path = require('path');

module.exports = {
resolve: {
alias: {
'@': path.resolve('resources/js'),
},
// Add .ts and .tsx as a resolvable extension.
extensions: [".ts", ".tsx", ".js"]
},
};
`

Then, let Mix know that it should handle the JavaScript code as TypeScript. Laravel Mix comes with built-in TypeScript support.

webpack.mix.js

-mix.js('resources/js/app.js', 'public/js')
+mix.ts('resources/js/app.ts', 'public/js')

That is it; you are all set! You can keep writing code the way you used to and utilize some TypeScript features and improve your front-end experience.

Run npm install for any additioal mix dependancies

npm run watch

link to repo: https://github.com/olivertembo/laravel-react-typescript-inertia-boilerplate

Top comments (0)